Render Image in React using Map

I am working on a React project that has all the data in a file called data.js. Within the file is a array with several objects inside. In a separate file call SuppList.js I am using the map method to loop through the array and display everything. I am able to display everything with the exception of the images in the array.

data.js

const supps = [
    {id: 1, suppName: "Protein", purpose: "Muscle Building and Recovery", pic: "./images/protein.png" },
    {id: 2, suppName: "Creatine", purpose: "Muscle Building, Strength and Recovery", pic: "./images/creatine.png"},
    {id: 3, suppName: "Minerals", purpose: "Health & Recovery", pic: "./images/minerals.png"},
    {id: 4, suppName: "Vitamin", purpose: "Health and Fat Loss", pic: "./images/vitamins.png" },
    {id: 5, suppName: "Fat-Loss", purpose: "Weight Loss & Recovery", pic: "./images/fat-loss.png" },
    {id: 6, suppName: "Pre-Workout", purpose: "Strength & Stamina", pic: "./images/pre-workout.png" },
]

export default supps;

SuppList.js

import elements from './data'

const SuppList = () => {
    return (
        <div>
            {elements.map((element) => (
                <div>
                <h3>{element.suppName}</h3>
                <p>{element.purpose}</p>
                <img src={element.pic} alt={element.id}/>
                </div>
                ))}
        </div>
    )
}
   
export default SuppList;

File Structure

1 thought on “Render Image in React using Map”

  1. You can use require.

    Something like this –

    const supps = [
      {
        ...
        pic: require("./images/protein.png"),
        ...
      },
    ]
    

    Then you can call this in map function:

    <img src={element.pic} alt={element.id}/>
    
    Reply

Leave a Comment