Setting a backgroundImage With React Inline Styles

Setting a backgroundImage With React Inline Styles

I’m trying to access a static image to use within an inline backgroundImage property within React. Unfortunately, I’ve run up dry on how to do this.
Generally, I thought you just did as follows:
import Background from ‘../images/background_image.png’;

var sectionStyle = {
width: “100%”,
height: “400px”,
backgroundImage: “url(” + { Background } + “)”

class Section extends Component {
render() {
return (


This works for tags. Can someone explain the difference between the the two?
works just fine.
Thank you!


Solution 1:

The curly braces inside backgroundImage property are wrong.

Probably you are using webpack along with image files loader, so Background should be already a String:
backgroundImage: "url(" + Background + ")"

You can also use ES6 string templates as below to achieve the same effect:

backgroundImage: `url(${Background})`

Solution 2:

If you are using ES5 –

backgroundImage: "url(" + Background + ")"

If you are using ES6 –

backgroundImage: `url(${Background})`

Basically removing unnecessary curly braces while adding value to backgroundImage property works will work.

Related:  Queuing Actions in Redux

Solution 3:

Inline style to set any image full screen:

  backgroundImage: "url(" + "" + ")",
  backgroundPosition: 'center',
  backgroundSize: 'cover',
  backgroundRepeat: 'no-repeat'

Solution 4:

You can also bring the image into the component by using the require() function.

<div style={{ backgroundImage: `url(require("images/img.svg"))` }}>

Note the two sets of curly brackets. The first set is for entering react mode and the second is for denoting object

Solution 5:

You can use Template Literals (enclosed with back-tick: `…`) instead for backgroundImage property like this:

backgroundImage: `url(${Background})`