I am new to react and trying to get background image with inline styling. But it's not working.
Showing error "url is not defined"
render() {
return (
<div className="phase1"
style ={ { backgroundImage: url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300') } }>
<input id="search"
type="text"
placeholder={this.state.search}
onChange={this.updateSearch.bind(this)}/>
<Link className="button1" to="Form"> + </Link>
</div>
)
}
}
export default App; Output: Method 5: Add background image from src/ folder If the image resides inside the src directory, the user can import it inside the component filer and set it as the background image. In this file, we will import the image and set it as a background image of the div element.
Make sure the image path is set correctly in the background-image url. Once you have made sure that your CSS file is linked correctly, also check that the image itself is set correctly. Again, you will want to open your code inspector in the browser to check.
You haven't specified when would you like to change backgroundImage , so I've created version which changes it with onClick : React. createClass({ getInitialState: function () { nextImg: false, }, handleClick: function () { this. setState({ nextImg: !
CSS values are always strings. Wrap the backgroundImage
value in quotation marks to make it a string:
<div className="phase1" style ={ { backgroundImage: "url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300')" } }>
Faced a similar problem and this did the trick for me
style={{backgroundImage: 'url(' + require('./images/sword.png') + ')'}}
the trick was adding the require
In my case, i have url with space on it, so it needs to be wrapped with quotes mark ex: 'url', because i got url (imagePath) directly from server.
<div style={{ backgroundImage: `url('${imagePath}')` }} />
Hope this helps someone.
In React putting relative paths for images like this
<div className="container-login100" style={{ backgroundImage: "url('./folder/images/bg-01.jpg')" }}>
doesn't seems to work as it is JSX, you need to import the image or require it
import BackgroundImage from './../frontend_authentication_copied/images/bg-01.jpg'
...
styles = {
backgroundImage: `url(${BackgroundImage})`
}
...
<div className="container-login100" style={this.styles}>
Just make sure you put all the images inside the src folder since relative imports are not supported from outside the src folder if create-react-app
is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With