505

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 (
      <section style={ sectionStyle }>
      </section>
    );
  }
}

This works for <img> tags. Can someone explain the difference between the two?

Example:

<img src={ Background } /> works just fine.

Thank you!

0

21 Answers 21

781

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})`
6
  • I should have added that to my question. I do have a width and height set (100% / 400px respectively). The issue arising is due to how react handles static images I believe.
    – Mmm Donuts
    Aug 28, 2016 at 23:23
  • Should one escape the '(", ')' and whitespace characters in the Background variable before concatenation as per w3.org/TR/CSS2/syndata.html#value-def-uri ?
    – qbolec
    Jul 12, 2017 at 10:31
  • 83
    Full syntax should look like this: style={{backgroundImage: "url(" + Background + ")"}}
    – mike
    Oct 12, 2017 at 18:37
  • 4
    just to expand @mike's comment, you need double curly braces because one is for React to enter is JS mode and one is to denote the new object. Aug 20, 2018 at 7:54
  • I am getting the error 'Section' is defined but never used' after giving this import Background from './background.jpg'; var sectionStyle = { width: "100%", height: "400px", backgroundImage: url(${Background}) }; class Section extends Component { render() { return ( <section style={ sectionStyle }> </section> ); } } Oct 22, 2018 at 9:07
98

Inline style to set any image full screen:

style={{  
  backgroundImage: "url(" + "https://images.pexels.com/photos/34153/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350" + ")",
  backgroundPosition: 'center',
  backgroundSize: 'cover',
  backgroundRepeat: 'no-repeat'
}}
3
  • Thanks a bunch, this is what I was looking for Aug 10, 2020 at 14:00
  • import Background from '../images/background_image.png'; Followed by the answer here did solve my problem, together is the best answer right now. Jan 7, 2021 at 14:15
  • import React, { useState, useEffect } from 'react'; import style from './style.module.css'; import authBg from '../../assets/Auth/authBg.png'; const Auth = () => { return ( <div style={{ backgroundImage: "url(" + authBg + ")", backgroundPosition: 'center', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', height: '100vh', width: '100vw' }}> daf </div> ); } export default Auth Sep 4, 2022 at 11:27
71

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.

3
  • 4
    For me in ES6 it was backgroundImage: `url("${Background}")`, as your ES6 example didn't work for me.
    – S..
    Oct 7, 2019 at 6:39
  • Hello Bharad, how would you go about it if you want to add more than one background image. Say for two images how would you do this? Thanks Jun 22, 2020 at 4:40
  • 2
    @S.. Thanks, that helped me. I was stuck.
    – Utkarsh
    Nov 6, 2020 at 16:29
36

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

2
  • What if the image path is a web URL instead of a local path? Something like https://images.com/myimage.png
    – Aminu Kano
    Aug 2, 2018 at 4:31
  • 5
    Ok I understand, when using web-based URL. I should just write url(https://images.com/myimage.png)
    – Aminu Kano
    Aug 2, 2018 at 4:35
22

It works for me:

  import Background from '../images/background_image.png';
    
  <div className=...
       style={{
              background: `url(${Background})`,
            }}
    >...</div>
18

For me what worked is having it like this

style={{ backgroundImage: `url(${require("./resources/img/banners/3.jpg")})` }}
14

You can use Template literals (enclosed with back-tick: `...`) instead. For backgroundImage property like this:

backgroundImage: `url(${Background})`
12

For a local File in case of ReactJS. Try

import Image from "../../assets/image.jpg";

<div
style={{ backgroundImage: 'url(' + Image + ')', backgroundSize: 'auto' }}
>Hello
</div>

This is the case of ReactJS with inline styling where Image is a local file that you must have imported with a path.

1
  • 1
    The properties are backgroundImage and backgroundSize in jsx
    – jpmc
    Apr 3, 2021 at 6:50
6

Change line 6 of your code from

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

to

  backgroundImage: "url(" + { Background.src } + ")"

and it will work.

4

try this:

style={{ backgroundImage: `url(require("path/image.ext"))` }}
3

updated to 17.05.22 instead:

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

do:

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

try this it worked in my case

backgroundImage: `url("${Background}")`
2

Sometimes your SVG will be inlined by React so you need quotes around it:

backgroundImage: `url("${Background}")`

otherwise it's invalid CSS and the browser dev tools will not show that you've set background-image at all.

1
  1. Copy the image to the React Component's folder where you want to see it.
  2. Copy the following code:
<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>
  1. Give a height to your .welcomer using CSS so that you can see your image in the desired size.
1
import React, { PureComponent } from 'react'
import logo from './logo.png';

class Home extends PureComponent {
    render() {
        return (
            <div>
                 <div
                    style={{
                        backgroundImage: `url("https://www.nicesnippets.com/image/imgpsh_fullsize.png")`, backgroundRepeat: 'no-repeat', width: '800px', height: '250px', color: 'blue'
                    }}>
                        Nice Snippets
                </div>
                    <hr />
                    <div
                        style={{
                            backgroundImage: `url(${logo})`, backgroundRepeat: 'no-repeat', width: '100%', height: '250px', color: 'blue'
                        }}>
                        Nice Snippets
                </div>
            </div>
        )
    }
}

export default Home
1
  • backgroundImage: url("https://www.nicesnippets.com/image/imgpsh_fullsize.png") or backgroundImage: url(${logo}) Apr 17, 2021 at 16:27
1

For ES6, please use

backgroundImage: `url("${Background}")
1
  • You are missing the endind tick ` in url(${Background})`.
    – user31782
    Aug 15 at 10:48
0

Just add required to file or url

<div style={
   {
      backgroundImage: `url(${require("./path_local")})`,      
   }
}
>

Or set in css base64 image like

div {
  background:
    url('data:image/gif;base64,R0lGODlhZQBhAPcAACQgDxMFABsHABYJABsLA')
    no-repeat
    left center;
}

You can use https://www.base64-image.de/ for convert

0

You can try this with by adding backticks on whole url

style={{backgroundImage:url(${val.image || 'http://max-themes.net/demos/grandtour/upload/Tokyo_Dollarphotoclub_72848283-copy-700x466.jpg'} ) }}

0

If you are using webpack you need to edit webpack.config.js and add this into it

module: {
  rules: [
 {
      test: /\.(png|jpe?g|gif)$/i,

     dependency: { not: ['url'] },
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 8192,
          },
        },
      ],
    },
  ],
}

if you use file-loader for rendering images you need to delete that like below:

    {
       test: /\.(png|jpe?g|gif)$/i,
       loader: 'file-loader',
    },

and in your css file instead of using background-image use background instead:

background: url(Background);

for more information about webpack with images see this also: https://v4.webpack.js.org/loaders/url-loader/

0

This worked for me

style={{ backgroundImage: `url(${require("../assets/pet4.jpeg").default})` }}
-2

You Can try usimg

backgroundImage: url(process.env.PUBLIC_URL + "/      assets/image_location")
1
  • This is not recommended since it will prevent webpack from knowing the asset. This will end in a cache miss if the react app is opened offline. Mar 13, 2020 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.