0

Is there any problem of using array to save src in it to display on component, it doesn't work?

    const imgs = [
      './../imgs/book1.jpg',
      './../imgs/book2.jpg',
      './../imgs/book3.jpg',
    ]
    const displayImg = imgBooks.forEach(img => {
      return (
           <figure>
            <img src={img} alt='book' />
          </figure>**strong text**
      )
    })

aya hosny
  • 57
  • 1
  • 1
  • 6
  • 1
    Shouldn't you be calling `foreach()` on the imgs array instead of the imgBooks array since the imgs array has the images in it. Otherwise it would be helpful to see the code where the variable imgBooks is created. – Raymond Mutyaba Jun 19 '20 at 22:34
  • 1
    `forEach` will not return an array so you want to use `map`. https://stackoverflow.com/a/34426481/1370487 – UX Nomaan Jun 20 '20 at 00:20

4 Answers4

2

The forEach() function for arrays returns undefined.

If you want to show several images at the same time, choose function that return array of components: map()

const displayImgs = imgBooks.map(img => {

If your component contain only components of the array, then you can simple return the array:

const imgBooks = [
  './../imgs/book1.jpg',
  './../imgs/book2.jpg',
  './../imgs/book3.jpg',
]
return imgBooks.map(img => (<figure><img src={img} alt='book' /></figure>));

Note the name of the array: imgBooks. There was imgs vs imgBooks typo(?) in the question.

SKi
  • 8,007
  • 2
  • 26
  • 57
2

You need to make sure that you transform your imgs array to another array that includes your JSX markup. From there, you need to iterate over your markup array for React to render each index of displayImg array.

const Component = () => {

    const imgs = [
        './../imgs/book1.jpg',
        './../imgs/book2.jpg',
        './../imgs/book3.jpg',
    ];

    const displayImg = imgs.map(img => {
        return (
            <figure>
            <img src={img} alt='book' />
            </figure>**strong text**
        )
    });


    return displayImg.map(img => img);

}
UX Nomaan
  • 432
  • 5
  • 11
1

If you are using create-react-app all your asset are bundled and they have different names. So, dynamic import so won't work. To overcome this you add all your images in public folder then

{ imgs.map((img) => (
   <figure>
      <img src={process.env.PUBLIC_URL + `/${data.photo}`}/>
   </figure>
))
Gnana Surya
  • 86
  • 1
  • 3
0

This worked for me:

     {productId && images.length > 0
                ? images.map((x, index) => (
                      <img
                        src={`${backend_url}${x}`}
                        key={index}
                        alt=""
                        className="h-[120px] w-[120px] object-cover m-2"
                      />
                  ))
                 :null 
                  ))}
Awara Amini
  • 307
  • 1
  • 6