Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
I am unable to use array elements in src attribute of img tag in React

I aim to render multiple images whose path I have already defined in an array called images. But when I want to use it in the src attribute of an img tag, for some reason it does not renders the image, even though the path is correct.

The code that I wrote in the react component was as follows:

let images=["../../../assets/temp.jpg", "../../../assets/temp2.jpg", "../../../assets/temp3.jpg"];
let n = images.length;
let imgArray = [];

for (let i = 0; i < n; i++) {
    imgArray.push(<img src={images[i]} alt="image cover" />);
}
return(
    <div>
        {imgArray}
    </div>
);

The above code does not render the image provided as a path in src. But if I import the path and then provide that imported element as the src, then it works fine.

The tech I have used in my project is React.js and Bootstrap

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

React uses JSX which cannot display arrays. In your code {imgArray} is an array of images, which you now need to loop through and convert to a JSX component/element.

The best approach is to use the array.map function built in to JS arrays. ​

// use "const" not let if the var doesn't change
const imgArray = [
    {
        key: 'uniqueid1',
        src: 'path/to/img.png',
    },
];

return
   ​<div>
       ​{
            imgArray.map(_img => <img 
                src={_img.src} 
                key={_img.key}
                alt="image cover" 
            />)
        }
  ​</div>
);

You'll note we now don't need the for loop either.

PS: Don't forget the "key" it's very important for React to reconcile the image elements you have created (and don't use the array index either)

More info:

  • List and Keys
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!