502

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!

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Mmm Donuts
  • 9,551
  • 6
  • 27
  • 49

21 Answers21

777

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})`
rgommezz
  • 13,536
  • 2
  • 18
  • 23
  • 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 '16 at 23:23
  • Should one escape the '(", ')' and whitespace characters in the Background variable before concatenation as per https://www.w3.org/TR/CSS2/syndata.html#value-def-uri ? – qbolec Jul 12 '17 at 10:31
  • 83
    Full syntax should look like this: `style={{backgroundImage: "url(" + Background + ")"}}` – mike Oct 12 '17 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. – Ciprian Tomoiagă Aug 20 '18 at 07: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 (
    ); } }
    – Pavanan M S Oct 22 '18 at 09:07
  • +1 to @mike answer. The accepted answer throws off my linter and keeps giving me grief with rando red squiggly lines that have been driving me crazy all day. – Tina Sep 25 '20 at 00:58
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'
}}
Pavindu
  • 2,684
  • 6
  • 44
  • 77
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
  • Thanks a bunch, this is what I was looking for – Prince Agrawal Aug 10 '20 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. – Arka Mallick Jan 07 '21 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 (
    daf
    ); } export default Auth
    – Chanrithisak Phok Sep 04 '22 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.

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

Pavindu
  • 2,684
  • 6
  • 44
  • 77
Tricky
  • 10,892
  • 1
  • 16
  • 15
22

It works for me:

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

For me what worked is having it like this

style={{ backgroundImage: `url(${require("./resources/img/banners/3.jpg")})` }}
eaglebearer
  • 2,060
  • 1
  • 13
  • 9
14

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

backgroundImage: `url(${Background})`
catphotos
  • 176
  • 2
  • 6
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.

lys
  • 949
  • 2
  • 9
  • 33
champion-runner
  • 1,489
  • 1
  • 13
  • 26
6

Change line 6 of your code from

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

to

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

and it will work.

taotao
  • 186
  • 1
  • 4
4

try this:

style={{ backgroundImage: `url(require("path/image.ext"))` }}
Hamza Khan
  • 108
  • 7
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.

Curtis
  • 2,486
  • 5
  • 40
  • 44
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.
Param Siddharth
  • 858
  • 2
  • 7
  • 20
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

For ES6, please use

backgroundImage: `url("${Background}")
Mujahidul Islam
  • 265
  • 4
  • 8
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}) }}

Paul Jere
  • 11
  • 4
-2

You Can try usimg

backgroundImage: url(process.env.PUBLIC_URL + "/      assets/image_location")
Jamilur Rahman
  • 69
  • 2
  • 12
  • 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. – Thomas Kekeisen Mar 13 '20 at 13:14