DEV Community

imad benmadi
imad benmadi

Posted on

Loading Images ReactJs

Hello Dev community
*I want to share with you a simple Image Loading Using Simple userEffect and a promise
*

  1. Fist of All , we create a component with a basic user interface

  2. 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";

Enter fullscreen mode Exit fullscreen mode

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");
        });
    }, []);
Enter fullscreen mode Exit fullscreen mode

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
      )}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

And That's it , We Done it !
a simple React image Loader with out any external library

Image description

Image description

Top comments (0)