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>
)
}
}
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
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 :)
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',
}}
>
来源:https://stackoverflow.com/questions/38794106/backgroundimage-is-not-working-in-react