I have tried everything I can think of, as well as Googled this to death. I cannot get React to load a background image using inline styles. Here is my code:
const url = './assets/backgrounds/terzo1.jpg'
const style = {
backgroundImage: `url(${url})`,
backgroundSize: 'cover',
}
const Layout = props => (
<div style={style}>
TEXT
</div>
)
export default Layout
My assets folder is in the same folder as the Layout component.
I will note that I am using Create-react-app.
Thanks
If you are using create-react-app, for loading images and using them in your JS and CSS files, there are two approaches one could take.
You can add your images in a directory inside public directory and use them as follows:
const style = {backgroundImage: 'url(/images/some-image.png)'}
If you want to use images relatively and import them dynamically, You should put your images in the same directory as the CSS or Component that you want to use image in. One of the best ways to structure your codebase is to use component scoped structure. In this way, all stuff related to a component will go in the component's directory. This contains the images too.
For more info:
This worked for me in a React 16.11.0 project created with create-react-app:
import emailIcon from '../../assets/images/footer/icons/email.png';
<div style={{ backgroundImage: "url(" + emailIcon + ")" }}></div>
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