Setting a backgroundImage With React Inline Styles

JavascriptReactjs

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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 - Javascript

It works for me:

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

Solution 6 - Javascript

For me what worked is having it like this

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

Solution 7 - Javascript

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

backgroundImage: `url(${Background})`

Solution 8 - Javascript

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.

Solution 9 - Javascript

try this:

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

Solution 10 - Javascript

Change line 6 of your code from

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

to

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

and it will work.

Solution 11 - Javascript

try this it worked in my case

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

Solution 12 - Javascript

updated to 17.05.22 instead:

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

do:

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

Solution 13 - Javascript

  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.

Solution 14 - Javascript

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.

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Solution 18 - Javascript

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/

Solution 19 - Javascript

This worked for me

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

Solution 20 - Javascript

You Can try usimg

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKrisView Question on Stackoverflow
Solution 1 - JavascriptrgommezzView Answer on Stackoverflow
Solution 2 - JavascriptHitesh SahuView Answer on Stackoverflow
Solution 3 - JavascriptRushikesh BharadView Answer on Stackoverflow
Solution 4 - JavascriptTrickyView Answer on Stackoverflow
Solution 5 - JavascriptDetonerView Answer on Stackoverflow
Solution 6 - JavascripteaglebearerView Answer on Stackoverflow
Solution 7 - JavascriptFawaz AbdullaView Answer on Stackoverflow
Solution 8 - Javascriptchampion-runnerView Answer on Stackoverflow
Solution 9 - JavascriptHamza KhanView Answer on Stackoverflow
Solution 10 - JavascripttaotaoView Answer on Stackoverflow
Solution 11 - JavascriptSaikiran RudraView Answer on Stackoverflow
Solution 12 - JavascriptDmitry SorokinView Answer on Stackoverflow
Solution 13 - JavascriptMourad MounimView Answer on Stackoverflow
Solution 14 - JavascriptCurtisView Answer on Stackoverflow
Solution 15 - JavascriptMohammad Ali AbdullahView Answer on Stackoverflow
Solution 16 - JavascriptliuspattView Answer on Stackoverflow
Solution 17 - JavascriptAhmed KhalilView Answer on Stackoverflow
Solution 18 - JavascriptAli AlavizadehView Answer on Stackoverflow
Solution 19 - JavascriptPaul JereView Answer on Stackoverflow
Solution 20 - JavascriptJamilur RahmanView Answer on Stackoverflow