1

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>
  );
}

3 Answers3

0

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})`
  }

}>

farooq
  • 1,603
  • 2
  • 17
  • 33
  • its working fine but sometimes is throwing a undefined value –  Jul 06 '22 at 06:30
  • Reduce imageArr.length value. That's the issue. let randomNum = Math.floor(Math.random() * (imageArr.length -1) ); – farooq Jul 06 '22 at 06:31
  • @ZUTIRBANBorthakur Or Use the below code to get 0'th index value . let randomNum = Math.floor(imageArr.length * Math.random()); – farooq Jul 06 '22 at 06:33
  • @ZUTIRBANBorthakur I have edited the code. Please replace the randomNum variable's value. – farooq Jul 06 '22 at 06:35
  • 1
    yuhu!!! it has start working, Thanks dude –  Jul 06 '22 at 06:35
0

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.

0

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",
            
            }}
           
          >

atum45 s
  • 115
  • 1
  • 6