skip to Main Content

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>
  );
}


3

Answers


  1. require.context needs to be interpreted by your bundler, not the runtime.

    Are you using webpack to bundle your code before running it in the browser?

    https://webpack.js.org/guides/dependency-management/#requirecontext

    Login or Signup to reply.
  2. 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>
      );
    }
    
    Login or Signup to reply.
  3. Well the one time that i needed to do something like this i used the following approach:
    I created an array of image names from the folder that contained the images.
    Here is how you can do it:

    const importAll = (r) => {
        let images = {};
        r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
        return images;
      };
      
      const images = importAll(require.context('./images', false, /.(png|jpe?g|svg)$/))
    

    Here is what I am doing:

    • require.context provides all the file paths that match the pattern (regex) provided
    • false in importAll function indivcates weather to include subdirectories or Not
    • Regex for checking files with image extensions

    Now that I have the names of images, i can simply iterate over the:

    <div className="image-gallery">
            {Object.keys(images).map((imageName, index) => (
              <img key={index} src={images[imageName]} alt={imageName} />
            ))}
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search