background-image in react component - javascript

I'm building a page and I want a material-ui element to have a background image using background-image CSS property. I have googled for it of course, and there are solutions but for some reason I can't see that image.
P.S.1: even changing that MUI element to regular hasn't helped me at all.
P.S.2: when I'm using inside container it shows, but that's not what I want.
UPDATE1: Tried adding height and width to container, still no luck...
import React from 'react';
import Paper from 'material-ui/Paper';
import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';
const styles = {
paperContainer: {
backgroundImage: `url(${"static/src/img/main.jpg"})`
}
};
export default class Home extends React.Component{
render(){
return(
<Paper style={styles.paperContainer}>
</Paper>
)
}
}

You have to import the image as the following, using the relative path.
import React from 'react';
import Paper from 'material-ui/Paper';
import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';
import Image from '../img/main.jpg'; // Import using relative path
const styles = {
paperContainer: {
backgroundImage: `url(${Image})`
}
};
export default class Home extends React.Component{
render(){
return(
<Paper style={styles.paperContainer}>
Some text to fill the Paper Component
</Paper>
)
}
}

I've found a fix for my case. Actually setting container height in pixels have helped.
Here's the code:
import React from 'react';
const styles = {
paperContainer: {
height: 1356,
backgroundImage: `url(${"static/src/img/main.jpg"})`
}
};
export default class Home extends React.Component {
render() {
return (
<div style={styles.paperContainer}>
</div>
)
}
}

I got this to work for material-ui, where the padding on my parent element was 24px so I added 48px to the width of the background image to make it work...
const styles = {
heroContainer: {
height: 800,
backgroundImage: `url(${"../static/DSC_1037.jpg"})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
width: `calc(100vw + 48px)`,
margin: -24,
padding: 24,
}
};
<Grid
container
direction="column"
justify="flex-end"
alignItems="right"
style={styles.heroContainer} >
<Grid item>Goes here</Grid>
</Grid>

Had the same issues while working with Material UI React and the Create React App. Here is the solution that worked for me. Note that I set up a webpack alias for the relative path
import BackgroundHeader from "assets/img/BlueDiamondBg.png"
const BackgroundHead = {
backgroundImage: 'url('+ BackgroundHeader+')'
}
<div style={BackgroundHead}>

Like Romainwn said, you need to import the image to the file. Make sure you use the relative path to parent, so instead of
static/src/img/main.jpg #looks for static folder from current file location
Do
/static/src/img/main.jpg #looks for file from host directory:
Another hack to do it would be adding an inline style tag to the component:
import React from 'react';
import Paper from 'material-ui/Paper';
import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';
import Image from '../img/main.jpg'; // Import using relative path
export default class Home extends React.Component{
render(){
return(
<Paper style="background:path/to/your/image;">
</Paper>
)
}
}

You can you sx props in MUI v5
import React from 'react';
import Paper from 'material-ui/Paper';
import Image from '../img/main.jpg';
export default class Home extends React.Component{
render(){
return(
<Paper sx={{ backgroundImage: `url(${Image})` }}>
</Paper>
)
}
}

Related

Using react-sticky to make a sticky header

I am trying to use the react-sticky package to make a sticky header, but my header keeps scrolling out of view. This is the package: https://www.npmjs.com/package/react-sticky
I am not sure if I am using the StickyContainer or Sticky compnents correctly. I am actually a bit confused about the "style" prop you're supposed to pass to the Sticky container.
If anyone can help, will be much appreciated. Thanks!
Here's the code for App.js:
import React, { Component } from 'react';
import './App.css';
import Header from './components/Header';
import Footer from './components/Footer';
import HomePage from './components/pages/HomePage';
import OurWork from './components/pages/OurWork';
import ContactUs from './components/pages/ContactUs';
import { BreakpointProvider } from 'react-socks';
import { StickyContainer, Sticky } from "react-sticky";
import { setDefaultBreakpoints } from 'react-socks';
setDefaultBreakpoints([
{ small: 0 },
{ medium: 700 }
]);
class App extends Component {
pageStyle = {
display: 'flex',
flexDirection: 'column'
}
render() {
return (
<BreakpointProvider>
<StickyContainer>
<div className="App">
<Sticky>
{({style}) => <Header style={style}/>}
</Sticky>
<div className="page" style={this.pageStyle}>
<HomePage />
<OurWork />
<ContactUs />
</div>
<Footer />
</div>
</StickyContainer>
</BreakpointProvider>
);
}
}
export default App;
Here is the Header component:
import React, { Component } from 'react';
import Logo from './Logo'
import NavBar from './NavBar';
import logo from '../images/transparent.png';
class Header extends Component {
headerStyle = {
height: 100,
margin: 20,
display: 'flex',
justifyContent: 'space-between',
zIndex: 10
};
render() {
return (
<div className="header" style={this.headerStyle}>
<Logo logo={logo}/>
<NavBar />
</div>
);
}
};
export default Header;
No external library is required for sticky header, check this resource React Table Sticky Header without external library
Demo
The trick is like
1 . divide the header and data part
Use fixed width for both
Wrap data container with a div , give that container div a fixed height,
allow
.container {
overflox-y : scroll;
height: 300px;
}

Setting container width on material-ui for React.js

I have recently started with React.js along with material-ui library. I am aware of the Grid system for layouts that material-ui uses. However, unlike Bootstrap, the container extends from end to end. Say, I want to create a global container to hold content which should have a max width of 1140px, what is the correct way to do it? Currently I am using withStyles provided by material-ui as shown by the code sample below
import React, { Component } from 'react';
import { withStyles } from '#material-ui/core/styles';
const styles = {
contentBody: {
maxWidth: '1140px',
marginLeft: 'auto',
marginRight: 'auto'
}
};
class ContentBody extends Component {
render() {
return (
<Grid container className={this.props.classes.contentBody}>
{this.props.children}
</Grid>
);
}
}
export default withStyles(styles)(ContentBody);

Material UI v0 ListItem Alignment Issue when using Custom Avatar Component

Material UI version: v0.20.0
I am trying to assign leftAvatar value via CustomAvatar component but it is not aligning as you can see in attached screenshot. Please help.
CustomAvatar: This component is working on some condition bases like if image is available the its
MemberList/index.js
import React, {Component} from 'react';
import {withRouter} from 'react-router-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {List, ListItem} from 'material-ui/List';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import CustomAvatar from 'routes/CustomAvatar';
class MemberList extends Component {
render(){<MuiThemeProvider>
<List>
<ListItem
leftAvatar={<CustomAvatar avatarPic={false}/>}
primaryText={"Mike Tailor"}
secondaryText={"This is first text"}
secondaryTextLines={1}
rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem>Add friend</MenuItem>
<MenuItem>Chat</MenuItem>
</IconMenu>}/>
<ListItem
leftAvatar={<CustomAvatar avatarPic={true}/>}
primaryText={"Kory Becker"}
secondaryText={"This is second text"}
secondaryTextLines={1}
rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem>Add friend</MenuItem>
<MenuItem>Chat</MenuItem>
</IconMenu>}/>
</List>
</MuiThemeProvider>}
}
export default withRouter(MemberList);
CustomAvatar/index.js
import React, {Component} from 'react';
import {withRouter} from 'react-router-dom';
import Avatar from 'material-ui/Avatar';
class CustomAvatar extends Component {
render(){
if(this.props.avatarPic){
return(<Avatar size={40} src={"http://www.example.com/myimage.png"} />)
}else{
return(<Avatar size={40}>A</Avatar>)
}
}
}
export default withRouter(CustomAvatar);
The cause of your problem
Your problem is caused because the material-ui v0 library expects the leftAvatar prop to be an Avatar component, and so relies on internal values of Avatar behind the scenes. Since your CustomAvatar is not directly an Avatar, material-ui does not find these internals and so the styling does not work.
Specifically, if you take a look at the source of ListItem, you'll notice a pushElement function that takes child components like leftAvatar and assigns styling by setting the style prop:
pushElement(children, element, baseStyles, additionalProps) {
if (element) {
const styles = Object.assign({}, baseStyles, element.props.style);
children.push(
React.cloneElement(element, {
key: children.length,
style: styles,
...additionalProps,
})
);
}
}
Your CustomAvatar makes no use of this style prop, so you never receive the necessary CSS styling. That's the cause of your layout issues.
You have a couple of options to fix this depending on whether you are willing to upgrade to v1 or not.
Code that fixes it
class CustomAvatar extends Component {
render() {
const { showPicture, ...other } = this.props;
if (showPicture) {
return (<Avatar size={40} {...other} src={"http://www.example.com/myimage.png"} />);
} else {
return (<Avatar size={40} {...other}>A</Avatar>);
}
}
}
As discussed above, the pushElement function sets the style prop. Right now, you're not using it, so your Avatars get no styling. The {...other} spreads this prop down into your Avatars so that they get the right styling and your layout works.
But, you should upgrade to v1
v1 should have a stable release in the early quarters of 2018, and it fixes a lot of these kinds of problems. Instead of spending time working through these kinds of issues and working with v0, you should upgrade and learn the new (and, imho, improved) way.
I also have faced same problem you could fix this by wrap your custom compoent into PAPER component of material-ui. Please see code below:
import React, {Component} from 'react';
import {withRouter} from 'react-router-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {List, ListItem} from 'material-ui/List';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import CustomAvatar from 'routes/CustomAvatar';
import Paper from 'material-ui/Paper';
class MemberList extends Component {
render(){<MuiThemeProvider>
<List>
<ListItem
leftAvatar={<Paper zDepth={2} circle={true}><CustomAvatar avatarPic={false}/></Paper>}
primaryText={"Mike Tailor"}
secondaryText={"This is first text"}
secondaryTextLines={1}
rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem>Add friend</MenuItem>
<MenuItem>Chat</MenuItem>
</IconMenu>}/>
<ListItem
leftAvatar={<Paper zDepth={2} circle={true}><CustomAvatar avatarPic={true}/></Paper>}
primaryText={"Kory Becker"}
secondaryText={"This is second text"}
secondaryTextLines={1}
rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem>Add friend</MenuItem>
<MenuItem>Chat</MenuItem>
</IconMenu>}/>
</List>
</MuiThemeProvider>}
}
export default withRouter(MemberList);

Content Component in Native Base React is not rendering

I desigining react native UI using Native base
library(http://docs.nativebase.io/Components.html#anatomy-headref). I am following their most basic example(the skeleton), but the Content Component is not showing up at all. Given that Most of the subcomponentes are depended on this, I am stuck on this library. I could render Grid which make sthis problem more weird for me. I am using there baseline example give in their documentation
http://docs.nativebase.io/Components.html#anatomy-headref ,only header is rendering.
import {Container,Header, Title, Button, Icon,Text} from 'native-base';
//Include Nativebase required components
import React from 'react';
import { StatusBar, StyleSheet ,View} from 'react-native'; //Most of the
react native components can be found in NativeBase
import { Font } from 'expo'; //to include font from expo.
// load up the child components
import BodyComponent from './body_container';
export default class ContainerApp extends React.Component {
//checking state for if font is loaded or not.
state = {
fontLoaded: false,
};
async componentDidMount() {
await Font.loadAsync({
'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'),
});
//Setting the state to true when font is loaded.
this.setState({ fontLoaded: true });
}
render() {
return (
this.state.fontLoaded && (
<BodyComponent />
)
);
}
}
body component
export default class BodyComponent extends React.Component {
constructor(props){
super(props);
}
render(){
return(
<Container>
<Header>
<Left>
<Button transparent>
<Icon name='menu' />
</Button>
</Left>
<Body>
<Title>Header</Title>
</Body>
<Right />
</Header>
<Content>
<Text>
This is Content Section
</Text>
</Content>
</Container>
)
}
}
the ui showing up like (Pixel XL android)
The UI
I created repo https://github.com/abdullah2891/react_native_practice
In my case, the version of native base is changed. So I revert it and convert native-base: ^2.15.2

Getting start with React and Material Ui

I'm starting to understand to work with Material Ui with React, I'm getting difficult to customize the components.
I have this example of the AppBar:
import React from 'react';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import FlatButton from 'material-ui/FlatButton';
const styles = {
title: {
cursor: 'pointer',
},
};
const AppBarExampleIconButton = () => (
<AppBar
title={<span styles={styles.title}>Portofolio</span>}
iconElementRight={<FlatButton label="Save" />} />
);
export default AppBarExampleIconButton;
I can customize the title, but I want to customize the AppBar, in the documentation the Style object Override the inline-styles of the root element. But I'm not understanding out it works, could someone help me?
Depend on of what you try to do you can customize the AppBar in a multiple way. One of them is if you only want to change the color etc to make a theme.js file and import it inside MuiThemeProvider
You do this in the root file of your app. Ex
// Material Setup
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
// Our Own Theme
import theme from './layout/theme';
const Root = () =>
<MuiThemeProvider muiTheme={getMuiTheme(theme)}>
<YourApp />
</MuiThemeProvider>;
SO if you want to do this inline like you say you make a object inside your styles object who is the css you want to apply to the appbar.
const styles = {
appbar: {
backgroundColor: 'blue'
}
}
And you call it as a props for the AppBar component
<AppBar style={styles.appbar} />
Also if you look at the docs here you can see the title have is own style props for him call titleStyle
Hope that can help you figured out.

Categories

Resources