Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React backgroundImage inline style not working

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

like image 701
Cazineer Avatar asked Dec 18 '17 20:12

Cazineer


2 Answers

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.

Images on public folder

You can add your images in a directory inside public directory and use them as follows:

const style = {backgroundImage: 'url(/images/some-image.png)'}

Images in the same directory as your CSS or JS files

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:

  • Use public folder for general assets outside of src directory
  • Import images directly into the component file in a scoped structure
like image 200
Farzad Yousefzadeh Avatar answered Oct 05 '22 05:10

Farzad Yousefzadeh


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>
like image 29
BBaysinger Avatar answered Oct 05 '22 05:10

BBaysinger