javascriptreactjsdirectory

How do I map() all images in a folder? | React.js and Vite


I need to map through all images in a folder in the public directory, and I was following this post to try to do that but I'm getting this error Uncaught (in promise) ReferenceError: require is not defined at GalleryPage.jsx:8:16

Here is my code

const images = require.context("/_fairImages", true);
const imageList = images.keys().map((image) => images(image));

function GalleryPage() { 
  return (
    <div className="galleryPage_v2">
      <div className="galleryWrapper">
        {imageList.map((image, index) => (
          <img src={image.default} alt="" className="galleryImg" />
        ))}
      </div>
    </div>
  );
}



Solution

  • Since you are using Vite you can try import.meta.glob it is similar to Webpack's require.context

    // Dynamically import all images in the _fairImages folder
    const images = import.meta.glob('/public/_fairImages/*.{png,jpg,jpeg,svg}', { eager: true });
    
    function GalleryPage() {
      const imageList = Object.values(images).map((image, index) => (
        <img key={index} src={image.default} alt={`Image ${index + 1}`} className="galleryImg" />
      ));
    
      return (
        <div className="galleryPage_v2">
          <div className="galleryWrapper">
            {imageList}
          </div>
        </div>
      );
    }