Skip to content

Instantly share code, notes, and snippets.

@pylnata
Last active September 26, 2019 04:51
Show Gist options
  • Save pylnata/6a80ba0fbe6e8df887fa4148e7b35c3f to your computer and use it in GitHub Desktop.
Save pylnata/6a80ba0fbe6e8df887fa4148e7b35c3f to your computer and use it in GitHub Desktop.
import and preloading a bunch og images in react app
/* Page.js */
import React, { useEffect, useState } from "react";
const Page = props => {
const [images, setImages] = useState({});
const [imagesReadyCnt, setImagesReadyCnt] = useState(0); // counter of preloaded images
useEffect(() => {
const importedImages = {};
let i = 0;
const r = require.context(
"./images/", // relative path to folder with images, that we want to be imported and preloaded
false, // with subfolders or not
/\.(png|jpe?g|svg)$/ // extensions of files
);
r.keys().forEach(item => {
const importedImg = r(item); // import image
importedImages[item.replace("./", "")] = importedImg; // name of file will be a key, path to file will be a value
const img = new Image();
img.onload = () => {
i++;
setImagesReadyCnt(i); // increase counter when image is loaded
};
img.src = importedImg;
});
setImages(importedImages);
}, []);
// if images are not loaded yet( means that counter != number of files in imported folder))
if (Object.keys(images).length !== imagesReadyCnt || imagesReadyCnt < 1) {
return "Loading ...";
}
return (
<>
<img src={images["bg.png"]} />
/* <Component img={images["apple.svg"]} /> */
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment