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