From 279cb8c4752b3ca1b83b87920a6d0b4486504596 Mon Sep 17 00:00:00 2001 From: plebbitor Date: Wed, 19 Apr 2023 14:16:04 +0200 Subject: [PATCH] fix imagebanner glitch --- src/components/ImageBanner.jsx | 36 +++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/components/ImageBanner.jsx b/src/components/ImageBanner.jsx index bc74a3d1..2e50de2d 100644 --- a/src/components/ImageBanner.jsx +++ b/src/components/ImageBanner.jsx @@ -2,32 +2,36 @@ import React, { useState, useEffect } from 'react'; import { useLocation } from 'react-router-dom'; const ImageBanner = () => { - const [currentImage, setCurrentImage] = useState(1); - const [isLoaded, setIsLoaded] = useState(false); + const [currentImage, setCurrentImage] = useState(null); const location = useLocation(); useEffect(() => { - const countImages = async () => { + let isMounted = true; + + const loadRandomImage = async () => { const images = await importAll(require.context('../../public/assets/banners', false, /\.(png|jpe?g|svg)$/)); - setCurrentImage(Math.floor(Math.random() * images.length) + 1); + const randomImage = Math.floor(Math.random() * images.length) + 1; + + const img = new Image(); + img.src = `${process.env.PUBLIC_URL}/assets/banners/banner-${randomImage}.jpg`; + + img.onload = () => { + if (isMounted) { + setCurrentImage(randomImage); + } + }; }; - setIsLoaded(false); - countImages(); + loadRandomImage(); + + return () => { + isMounted = false; + }; }, [location.key]); - useEffect(() => { - setIsLoaded(false); - const img = new Image(); - img.src = `${process.env.PUBLIC_URL}/assets/banners/banner-${currentImage}.jpg`; - img.onload = () => { - setIsLoaded(true); - }; - }, [currentImage]); - return ( <> - {isLoaded && } + {currentImage && } ); };