Search code examples
reactjsurlwebpackimportbackground-image

How to import images dynamically to set as the url path for background image property in react


I have an assets folder that store all my images.
And in the assets folder I also have a json file that has objects each has a key that holds the relative path to an image.

[
  {"url":"../assets/image1"},
  {"url":"../assets/image1"}
]

I want to be able to map through these objects in the json file and dynamically make a component that will have a div where its background-image property will be a url() and the argument of the path will be supplied through each json object.
like this:

function Box(props) {
  const style = {
    backgroundImage: `url(${props.imageURL})`
  }
  return(<div style={style}></div>)
}

It works if I specifically import the image path like this, at the top

import imageURL from '../assets/image1';
...
    backgroundImage: `url(${imageURL})`
...

But then that way it won't be dynamic.

How do I import import images dynamically to set as the url path for the background-image property?


Solution

  • Answer inspired by @chonnychu
    I ended up making a component that handles all the imports, and exporting all the imported stuff at the end.
    While this is not the optimal solution, but it's an acceptable amount of manual work.

    import box1image from "../assets/TimeSeriesAnalysis.png";
    
    const boxInfo = [
      {
        id: 1,
        image: box1image,
        title: "Box 1",
        description:
          "Box 1 is the first box",
      },
    ];
    
    export default boxInfo;