Files
5chan/src/components/ImageBanner.jsx
T

40 lines
1.1 KiB
React
Raw Normal View History

2023-02-08 21:49:36 +01:00
import React, { useState, useEffect } from 'react';
2023-03-03 14:44:34 +01:00
import { useLocation } from 'react-router-dom';
2023-02-08 21:49:36 +01:00
const ImageBanner = () => {
const [currentImage, setCurrentImage] = useState(1);
2023-03-04 22:11:45 +01:00
const [isLoaded, setIsLoaded] = useState(false);
2023-03-03 14:44:34 +01:00
const location = useLocation();
2023-02-08 21:49:36 +01:00
useEffect(() => {
2023-03-06 13:55:31 +01:00
const countImages = async () => {
const images = await importAll(require.context('../../public/assets/banners', false, /\.(png|jpe?g|svg)$/));
setCurrentImage(Math.floor(Math.random() * images.length) + 1);
};
2023-03-04 22:11:45 +01:00
setIsLoaded(false);
2023-03-06 13:55:31 +01:00
countImages();
2023-03-03 14:44:34 +01:00
}, [location.key]);
2023-02-08 21:49:36 +01:00
2023-03-04 22:11:45 +01:00
useEffect(() => {
setIsLoaded(false);
const img = new Image();
2023-03-06 13:55:31 +01:00
img.src = `${process.env.PUBLIC_URL}/assets/banners/banner-${currentImage}.jpg`;
2023-03-04 22:11:45 +01:00
img.onload = () => {
setIsLoaded(true);
};
}, [currentImage]);
2023-02-08 21:49:36 +01:00
return (
2023-03-04 22:11:45 +01:00
<>
2023-03-06 13:55:31 +01:00
{isLoaded && <img id="banner-img" src={`${process.env.PUBLIC_URL}/assets/banners/banner-${currentImage}.jpg`} alt="banner" />}
2023-03-04 22:11:45 +01:00
</>
2023-02-08 21:49:36 +01:00
);
};
2023-03-06 13:55:31 +01:00
// Helper function to import all images from a directory
function importAll(r) {
return r.keys().map(r);
}
2023-03-21 11:17:54 +01:00
export default ImageBanner;