Search code examples
reactjsimagerequirereact-props

How can I dynamically load an image from my assets folder based on props in ReactJS?


I am building a simple web app displays a panel of information for each item in a database. Part of this information is a picture that I would like to display alongside it.

This code in the panel component used to work fine:

<td>
  <img src={require(`../../../assets/images/${props.image_name}.png`)} />
</td>

However, I recently updated my modules and the images are now broken. Is there a new recommended way to do this?


Solution

  • The best way to do that should be this:

    First: make index.js inside image folder then import all image

    import img1 from "./image_name.jpg";
    export const image_name = img1;
    

    or

    export const image_name = require("./image_name.jpg")
    

    Second: import them like this:

    import * as images from "../assets/img";
    

    Last: use them like module

     images.image_name 
    

    Or

    <img src={images[props.image_name])} />