Setting a Backgroundimage with React Inline Styles

Setting a backgroundImage With React Inline Styles

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

react inline style backgroundImage not shown

You need to import the image.

import imageFilename from '../../../assets/img/picture.jpg';

Setting a dynamic backgroundImage With React inline styles

There are a lot of similiar questions so I wont repeat my self, to understand why this code doesn't work you should research on how Webpack works.

One option it so move images to static folder, this snippet is valid:

const imageUrl = 'static/img/file-name.jpg';
<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>

If you want to import from src folder, you must import if beforehand (file urls are resolved in build time due to webpack).

// or use require, doesn't metter
import img1 from '../img/cat.jpg';
import img2 from '../img/dog.jpg';

const imageURL = filenames[0] === cat ? img1 : img2;
<div style={{ background: `url(${imageURL}) no-repeat`}}/>

Inline background-image in React

I figured it out, you can't just put a link straight into url. You need to require it first.

var bg=require('../../../../images/products/cards/main.jpg')
return (
<div className="ProductItem">

{/* Background Image */}
<div className='background-image' style ={ { backgroundImage: "url("+bg+")" } }></div>

React backgroundImage inline style not working

If you are using create-react-app, for loading images and using them in your JS and CSS files, there are two approaches one could take.

Images on public folder

You can add your images in a directory inside public directory and use them as follows:

const style = {backgroundImage: 'url(/images/some-image.png)'}

Images in the same directory as your CSS or JS files

If you want to use images relatively and import them dynamically, You should put your images in the same directory as the CSS or Component that you want to use image in. One of the best ways to structure your codebase is to use component scoped structure. In this way, all stuff related to a component will go in the component's directory. This contains the images too.

For more info:

  • Use public folder for general assets outside of src directory
  • Import images directly into the component file in a scoped structure


Related Topics



Leave a reply



Submit