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

42 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 = () => {
2023-09-23 10:30:48 +02:00
const [currentImage, setCurrentImage] = useState(null);
const location = useLocation();
2023-02-08 21:49:36 +01:00
2023-09-23 10:30:48 +02:00
const parentRoute = location.pathname.split('/').slice(0, 3).join('/');
2023-04-19 14:16:04 +02:00
2023-09-23 10:30:48 +02:00
useEffect(() => {
let isMounted = true;
2023-04-19 14:16:04 +02:00
2023-09-23 10:30:48 +02:00
const loadRandomImage = async () => {
const images = await importAll(require.context('../../public/assets/banners', false, /\.(png|jpe?g|svg)$/));
const randomImage = Math.floor(Math.random() * images.length) + 1;
2023-04-19 14:16:04 +02:00
2023-09-23 10:30:48 +02:00
const img = new Image();
img.src = `${process.env.PUBLIC_URL}/assets/banners/banner-${randomImage}.jpg`;
2023-03-06 13:55:31 +01:00
2023-09-23 10:30:48 +02:00
img.onload = () => {
if (isMounted) {
setCurrentImage(randomImage);
}
};
};
2023-04-19 14:16:04 +02:00
2023-09-23 10:30:48 +02:00
loadRandomImage();
2023-02-08 21:49:36 +01:00
2023-09-23 10:30:48 +02:00
return () => {
isMounted = false;
};
}, [parentRoute]);
2023-09-16 21:40:23 +02:00
2023-09-23 10:30:48 +02:00
return <>{currentImage && <img id='banner-img' src={`${process.env.PUBLIC_URL}/assets/banners/banner-${currentImage}.jpg`} alt='banner' />}</>;
2023-02-08 21:49:36 +01:00
};
2023-03-22 16:23:32 +01:00
export function importAll(r) {
2023-09-23 10:30:48 +02:00
return r.keys().map(r);
2023-03-06 13:55:31 +01:00
}
2023-09-16 21:40:23 +02:00
export default ImageBanner;