Search code examples
reactjsjsxreact-props

How to load local images in React through props?


I have placed downloaded images in an images folder inside my public folder. The images are numbered from 1 to 10.

images directory structure

In my App.js file I am passing the id of each image to Component.js.

return(
  <div>
    {info.map((users, i) => {
      return(
        <Component key={i} id={info[i].id} />
      )
    })}
  </div>
)

And in the Component.js file, I am rendering an image like this:

<img alt='image' src='/images/{this.props.id}.jpg'/>

My vision is that I will send an id through props from App.js and in Component.js I will use that id for {this.props.id}.jpg to display the id's respective image. The page is loading and there are no errors showing up but I am not able to see the images. I then changed the images folder's location and tried doing this:

<img alt='image' src={require(`D:/project-name/src/images/${this.props.id}.jpg`)}/>

But still facing the same issue. Please help me solve this issue.


Solution

  • The issue is in your image tag. Try making the string a template string and don't forget to add the missing dollar sign before {this.props.id}.

    <img alt='image' src={`/images/${this.props.id}.jpg`} />