I am using Create-React-App with react-router-dom and looking to use dynamic import to load images from different directory.
Something like this
// visit the url will show images in projectName folder
pseudo.com/category/projectName
I've read the document of Webpack, it said the import() must have some information about the module is located.So I passed the last level of directory name rather than the whole directory as props to component.
This is my current way of importing(which does not work)
// ImageGallery.js
function ImageGallery({ galleryDirectory }) {
const [images, setImages] = useState([]);
useEffect(() => {
const loadImages = async () => {
try {
const imageContext = await import(
`./img/portfolio/${galleryDirectory}`
);
const imagePaths = imageContext.keys();
const imageComponents = await Promise.all(
imagePaths.map(async (path) => {
const module = await import(
`./img/portfolio/${galleryDirectory}/${path.slice(2)}`
);
const imageSrc = module.default;
return <img keys={path} src={imageSrc} alt={path} />;
})
);
setImages(imageComponents);
} catch (error) {
console.error("error loading images:", error);
}
};
loadImages();
}, [galleryDirectory]);
return <>{images}</>;
}
export default ImageGallery;
The file which contains data of each project
// projectData.js
export const projectData = [
{
id: 1,
category: "graphic",
name: "graphic_project_1",
portfolioCover: require("../img/portfolio/cover/graphic1_cover.jpg"),
workCover: require("../img/portfolio/cover/graphic1_cover.jpg"),
galleryDirectory: "graphic1"
},
{
id: 2,
category: "website",
name: "website_project_1",
portfolioCover: require("../img/portfolio/cover/web1_cover.jpg"),
workCover: require("../img/portfolio/cover/web1_cover.jpg"),
galleryDirectory: "web1"
}
];
The folder structure is
public/
src/
api/
projectData.js
img/
portfolio/
graphic1/
graphic_1.jpg
graphic_2.jpg
...
web1/
web_1.png
web_2.jpg
...
App.js
ImageGallery.js
SingleProject.js
index.js
The error message module not found error
Here's the Codesandbox