admin管理员组

文章数量:1125980

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!

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!

Share Improve this question edited Aug 10, 2020 at 20:45 HoldOffHunger 20.8k11 gold badges118 silver badges146 bronze badges asked Aug 28, 2016 at 20:54 Mmm DonutsMmm Donuts 10.3k6 gold badges30 silver badges60 bronze badges 0
Add a comment  | 

23 Answers 23

Reset to default 809

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

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

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.

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

It works for me:

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

For me what worked is having it like this

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

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

backgroundImage: `url(${Background})`

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.

Change line 6 of your code from

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

to

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

and it will work.

try this:

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

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.

updated to 17.05.22 instead:

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

do:

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

try this it worked in my case

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

For ES6, please use

backgroundImage: `url("${Background}")
  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.
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

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

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

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/

This worked for me

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

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

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

//then use in div inside style =

hello world

You Can try usimg

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

本文标签: javascriptSetting a backgroundImage With React Inline StylesStack Overflow