Hello Dev community
*I want to share with you a simple Image Loading Using Simple userEffect and a promise
*
Fist of All , we create a component with a basic user interface
we import ower images from the Public folder
I have an example in here
import bernuilt from "../../../public/bernuilt.jpg";
import benomial from "../../../public/benomial.jpg";
import uniformDiscret from "../../../public/uniformDiscret.jpg";
import HyperGeomitrique from "../../../public/HyperGeomitrique.jpg";
import Geomitrique from "../../../public/Geomitrique.jpg";
import Poisson from "../../../public/Poisson.jpg";
and then this is the useEffect function that does the word for us
const [imagesLoaded, setImagesLoaded] = useState(false);
useEffect(() => {
const imageLoader = new Promise((resolve, reject) => {
const images = [bernuilt, benomial, uniformDiscret, HyperGeomitrique, Geomitrique, Poisson];
let loadedCount = 0;
images.forEach((imageSrc) => {
const img = new Image();
img.onload = () => {
loadedCount++;
if (loadedCount === images.length) {
resolve();
}
};
img.onerror = () => {
reject();
};
img.src = imageSrc;
});
});
imageLoader.then(() => {
setImagesLoaded(true);
}).catch(() => {
console.error("Error loading images");
});
}, []);
and then Lastly to integrate between the Loading and the UI we use this simple Logic
{!imagesLoaded ? (
<div className="w-full h-full flex items-center justify-center">
<span className="loader"></span>
</div>
) : (
// you code here
)}
and for the .loader CSS class We use this CSS animation Code
.loader {
width: 40px;
height: 40px;
border: 5px solid #353535;
border-bottom-color: transparent;
border-radius: 50%;
display: inline-block;
box-sizing: border-box;
animation: rotation 1s linear infinite;
}
@keyframes rotation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
And That's it , We Done it !
a simple React image Loader with out any external library
Top comments (0)