532

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

23 Answers 23

813

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})`
Sign up to request clarification or add additional context in comments.

6 Comments

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.
Should one escape the '(", ')' and whitespace characters in the Background variable before concatenation as per w3.org/TR/CSS2/syndata.html#value-def-uri ?
Full syntax should look like this: style={{backgroundImage: "url(" + Background + ")"}}
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.
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> ); } }
|
104

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'
}}

2 Comments

import Background from '../images/background_image.png'; Followed by the answer here did solve my problem, together is the best answer right now.
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
73

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.

2 Comments

For me in ES6 it was backgroundImage: `url("${Background}")`, as your ES6 example didn't work for me.
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
40

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 Comments

What if the image path is a web URL instead of a local path? Something like https://images.com/myimage.png
Ok I understand, when using web-based URL. I should just write url(https://images.com/myimage.png)
24

It works for me:

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

Comments

18

For me what worked is having it like this

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

Comments

15

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

backgroundImage: `url(${Background})`

Comments

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 Comment

The properties are backgroundImage and backgroundSize in jsx
6

Change line 6 of your code from

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

to

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

and it will work.

Comments

4

try this:

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

Comments

4

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 Comment

thanks, tried a few on this page and this answer worked for me
3

updated to 17.05.22 instead:

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

do:

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

Comments

2

try this it worked in my case

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

Comments

2

For ES6, please use

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

1 Comment

You are missing the endind tick ` in url(${Background})`.
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.

Comments

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 Comment

backgroundImage: url("https://www.nicesnippets.com/image/imgpsh_fullsize.png") or backgroundImage: url(${logo})
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

Comments

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'} ) }}

Comments

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/

Comments

0

This worked for me

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

Comments

0

if you want to use backgroundImage: url() to display an image you have two ways

1- if the image path include spaces or special chars use this
backgroundImage: url("${props.img}"),

2- if the image path doesn't include any spaces or special chars use this backgroundImage: url(${props.img}),

Comments

0

//first import the image import heroImg from '../src/image/heroImg.png'

//then use in div inside style =

hello world

Comments

-2

You Can try usimg

backgroundImage: url(process.env.PUBLIC_URL + "/      assets/image_location")

1 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.