Home > Enterprise >  How to change background image set with inline style mapping an array?
How to change background image set with inline style mapping an array?

Time:10-19

I am trying to change my background image which is set with inline style mapping an array as follow:

const changeBgImage = () => {
  let bgImages = [
    "/ihpbnkKoningzaal12Owres.jpg",
    "https://static.wixstatic.com/media/28661c_577a107e4ea648a18285371cd03bd121f000.jpg/v1/fill/w_1263,h_649,al_c,q_85,usm_0.33_1.00_0.00,enc_auto/28661c_577a107e4ea648a18285371cd03bd121f000.jpg",
  ];
  setInterval(() => {
    bgImages.map((bgImg, index) => {
      console.log(bgImg, index);
      window.document.getElementById("bg-container").style.backgroundImage = `url(${bgImg})`;
      window.document.getElementById("bg-container").style.backgroundSize =
        "cover";
      window.document.getElementById("bg-container").style.backgroundRepeat =
        "no-repeat";
      window.document.getElementById("bg-container").style.backgroundPosition =
        "center";
      window.document.getElementById(
        "bg-container"
      ).style.backgroundAttachment = "fixed";
    });
    // window.document.getElementById("bg-container").style.backgroundImage =
    //   "url('/ihpbnkKoningzaal12Owres.jpg')";
  }, 5000);
};

I call the above function inside a useEffect so the background image can change on page load as per below:

 useEffect(() => {
    changeBgImage();
    
    );
  }, []);

for some reason i don't understand it does not work, how ever, if I don't map though the array and run the commented line at the end, it works fine which make me think the issue is with the map function maybe.

Can someone advise what i do wrong, please?

CodePudding user response:

i don't get it why you are using set interval or even mapping through an array anyway in the mapped version you never set the background image of "bg-container" that's why it works differently when being mapped

CodePudding user response:

Seems to me that you forgot to put quotes there. Running url(${bgImg}) on first element will result to url(/ihpbnkKoningzaal12Owres.jpg), try url('${bgImg}') instead.

Also in react it is better to use refs instead of document.getElement

CodePudding user response:

Let's change your element background randomly according to backgrounds array.

// in-range random number generator
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min)   min;
}

const fn = () => {

   // random index for bgImages array - a number from 0 to array.length - 1,
   // -1 is because this array length is 2, but last index is 1.
 
   const randomIndex = getRandomArbitrary(0, bgImages.length - 1);

   // all styles for html element
   const styles = {
      backgroundSize: "cover",
      backgroundRepeat: "no-repeat",
      backgroundPosition: "center",
      backgroundAttachment: "fixed",
      backgroundImage: `url("${bgImages[randomIndex]}")`
   }
   
   // reference to html element, no need to make a search for your element in  DOM for every css property
   const bgCont = document.getElementById("bg-container");

   // walking over styles object and applying css props to html element
   Object.entries(styles).forEach(([key, value]) => {
       bgCont.style[key] = value
   })
   
}

setInterval(fn, 5000)

Here we can make some improvement like applying css class to element and changing only single property, initializing bgCont outside the function and other stuff. This is a very straight, fast and unoptimal approach.

  • Related