here for the testing purpose I have added only one background image, but what I actually need to do is to change the background on each reload. That means I need to pass an array where the path of all the images will be there and the background should change on each reload. The code is attached below. The whole project is based on react
function App() {
return (
<div className="App" style={
{
backgroundImage: `url("back.jpg")`
}
}>
<div className='container'>
<div className='container'>
<Header/>
<Footer/>
</div>
</div>
</div>
);
}
Just store the image URLs into one array and then generate random number . And then get the random index of an array using the generated number.
let imageArr = ["back.jpeg", "front.jpeg", "forward.jpeg", "backward.jpeg", "other.jpeg"];
let randomNum = = Math.floor(imageArr.length * Math.random());
let randomImage = imageArr[randomNum];
console.log(randomImage);
Add the randomImage variable into your div's backgroundImage propery as follows.
<div className="App" style={
{
backgroundImage: `url(${randomImage})`
}
}>
Just wrtie the background code like this:
backgroundImage: `url('${backgroundUrlList[Math.floor((Math.random() * backgroundUrlList.length))]}')`
You should define your own backgroundUrlList by the way.
You can make an array of images , and set the state of the first one
Important this will change image every 5 sec ! you can change the interval in the useEffect . !If you want to change just every time when render , make a Math.random from the lenght of arrayOfImages.length
const imgArray = [image1, image2, image3, image4, image5];
const [state, setState] = useState({ img: 0 });
Don't forget to import the images
import image1 from "../assets/im1.jpeg";
import image2 from "../assets/im2.jpeg";
import image3 from "../assets/im3.jpeg";
import image4 from "../assets/im4.jpeg";
import image5 from "../assets/im5.jpeg";
and in a useEffect change the state of image
useEffect(() => {
const interval = setInterval(() => {
if (state.img === 4) {
setState((prev) => ({
...prev,
img: 0,
}));
} else {
setState((prev) => ({
...prev,
img: state.img + 1,
}));
}
}, 5000);
return () => clearInterval(interval);
}, [state.img]);
In your div set the backgroundImage
<section
class="hero-wrap hero-wrap-2 js-fullheight ftco-degree-bg"
style={{
backgroundImage: `url(${imgArray[state.img]})`,
// backgroundSize: "cover",
backgroundPosition: "center",
// overflow: "hidden",
}}
>