Reputation: 1259
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>
)
}
}
Upvotes: 26
Views: 73679
Reputation: 399
I was battling with this same issue this morning but i was able to fix it with below snippet.
<div
className="col-md-4 col-xs-12"
style={{
backgroundImage: `url(${require('./path/img.png')})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
}}
></div>
Upvotes: 4
Reputation: 33
I'm not sure why, but for me only one way that works is like this:
<div style={{backgroundImage: `url(${require("./images/your_image").default})`}}></div>
Without the .default
no error would occur, but the image simply would not appear in the html. I hope I helped someone ;)
Upvotes: 4
Reputation: 617
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.
Upvotes: 19
Reputation: 4297
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.
Upvotes: 10
Reputation: 5283
I've stumbled upon this thread today. I was in need to change the backgroundImage
property dynamically, so require
was not an option. In my ElectronJS app all I did was:
const imageFilePath = './some/dynamic/path/here';
const style = { backgroundImage: `url('file://${imageFilePath}')` };
Hope this helps somebody :)
Upvotes: 5
Reputation: 431
Faced a similar problem and this did the trick for me
style={{backgroundImage: 'url(' + require('./images/sword.png') + ')'}}
the trick was adding the require
Upvotes: 32
Reputation: 44900
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')" } }>
Upvotes: 36