0

I have images in public/assets/images. There's 100 images with different file extension (png, jpg, webp, etc). I'm trying to make a list of images and those images are taken from public/assets/images. How to iterate through public/assets/images so i can get all images filename in an array?. And here's how my code look like.

const ImageList = () => {
  const filenames = [an array consist of image filename in public/assets/images]
  return (
    <ul>
      {
        filenames.map(filename => {
          return <li>
            <img src={filename} alt={filename} />
          </li>
        })
      }
    </ul>
  )
}

export default ImageList

Here's my project structure

public
-assets
--images
--- image1.jpg
--- image2.png
--- image3.webp
--- ...
src
-components
--ImageList.js
--...
App.js

2 Answers2

2

I got from this! Change './' to your image directory (try to find it when you access the web because it is managed by webpack).

function importAll(r) {
  return r.keys().map(r);
}

const ImageList = () => {
  const filenames = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));
  return (
    <ul>
      {
        filenames.map(filename => {
          return <li>
            <img src={filename} alt={filename} />
          </li>
        })
      }
    </ul>
  )
}

export default ImageList
Savior
  • 36
  • 1
1

Just remove public in the path because the index.html is the same location with assets

const filenames = ["./assets/images/image1.jpg"]
Viet
  • 12,133
  • 2
  • 15
  • 21