admin管理员组文章数量:1296911
On my React app, I have a History page which displays a lot of pictures for each year. Since I can't use a backend for this project, all my pictures are in my frontend. Having hundreds of them, importing them manually is not a possibility.
I first tried this in my YearHistory
component :
const { year } = useParams();
const pictures = useMemo(() => {
const images = require.context(`../../assets/history/${year}/images`, true);
const imagesList = images.keys().map((image) => images(image));
const imagesArray = imagesList.map((image, index) => {
return <img key={index} src={image} alt={`image-${index}`} />;
});
return imagesArray;
}, [year]);
But you can't have a dynamic url with require.context()
and you can't use this function inside a React component anyway.
So I came up with the idea of having a utility file indexing the urls like this (I just copied one year here for clarity) :
const images2024 = require.context(`../../assets/history/2024/images`, true);
export const indexedImports = {
2024: images2024,
};
Which I then imported in the YearHistory
component like this :
const { year } = useParams();
const pictures = useMemo(() => {
const images = indexedImports[year];
const imagesList = images.keys().map((image) => images(image));
const imagesArray = imagesList.map((image, index) => {
return <img key={index} src={image} alt={`image-${index}`} />;
});
return imagesArray;
}, [year]);
But using this method makes my app crash without much information.
Any idea on how I could dynamically import my pictures folders ?
Edit : it looks like there is just too much pictures. The first folder I tried to test it out had 700+ pictures, which was too much (terminal exited with The build failed because the process exited too early. This probably means the system ran out of memory or someone called
kill -9 on the process.
. I tried with a folder which has 25 of them and it works fine with my indexing file solution. Is there any way to load hundreds of pictures on the frontend or is putting them on a backend the only way ?
本文标签: javascriptHow to import pictures folder dynamically in ReactStack Overflow
版权声明:本文标题:javascript - How to import pictures folder dynamically in React? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741611559a2388289.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论