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