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
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
Since you are using Vite you can try
import.meta.glob
it is similar to Webpack’srequire.context
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:
Here is what I am doing:
Now that I have the names of images, i can simply iterate over the: