Home > Software design >  Set backgroundImage array mapping using React inline styles
Set backgroundImage array mapping using React inline styles

Time:06-08

This is my folder structure:

src
   --Assets/
            --pug.svg
            --scss.svg
   --Layouts/
            --Skills/
                    --Skills.js
   --App.js

My array

const skills = [
  {
    id: 1,
    title: 'Pug',
    image: 'url(../../Assets/pug.svg)'
  },
  {
    id: 2,
    title: 'SCSS',
    image: 'url(../../Assets/scss.svg)'
  }

In Skills.js I want to set the backgroundImage using React's inline styles, but it doesn't work. I don't get any error, just the backgroundImage doesn't show up.

{
    skills.map(skill => (
        <motion.div className='column' key={skill.id} variants={container}>
           <div className='skill'>
             <div className='skill-image' style={{ backgroundImage: `${skill.image}`  }}/>
             <h3>{skill.title}</h3>
           </div>
        </motion.div>
      ))
   }

CodePudding user response:

You cannot use relative paths in background-image directly. Those won't be resolvable from browser perspective as modules aren't preserved, but bundled together instead.

Now, to make it work you can:
a) move your assets (images) to /public and then replace their paths with /pug.svg and /scss.svg.
b) import images directly in your JavaScript files using import

First option uses special /public directory. Assets located there can be reached by browser. See https://create-react-app.dev/docs/using-the-public-folder/ for details.

As for importing assets directly, this heavily relies on your bundler (Webpack). It will resolve those files while building and attach them to the output. If you want to know more visit https://create-react-app.dev/docs/adding-images-fonts-and-files.

Look at following code block. I've replaced your relative paths with URLs returned from import statements. You can look them up using console.log to see the difference.

import pugImage from '../../Assets/pug.svg';
import scssImage from '../../Assets/scss.svg';

const skills = [
  {
    id: 1,
    title: 'Pug',
    image: pugImage,
  },
  {
    id: 2,
    title: 'SCSS',
    image: scssImage,
  }
]

CodePudding user response:

Issue is that your Assets folder is not public. If you move the images from Assets to public/images, you will see the background will start working -

You have two options now -

import the image

import background from "../../Assets/pug.svg";
backgroundImage: `url(${background})`

OR

use require

backgroundImage: `url(${require("../../Assets/pug.svg")})`

CodePudding user response:

Change backgroundImage to background

{
    skills.map(skill => (
        <motion.div className='column' key={skill.id} variants={container}>
           <div className='skill'>
             <div className='skill-image' style={{ background: `${skill.image}`  }}/>
             <h3>{skill.title}</h3>
           </div>
        </motion.div>
      ))
   }
  • Related