We're building a website in React. We want the background-image to cycle through an array of 10 different backgrounds. Right now we are using a divStyle that sets a background-image with a url that is updated every 10 seconds to request the next image. This works, however this causes a request to the server every 10 seconds. Is there a way to load an array of images once in the componentDidMount
(so on loading the webpage for the first time) and then just cycling through this array?
We tried making an array with Image()
objects, but the background-image
property only accepts a url. We also tried rendering the array with Image()
objects in the render method of React, but we then get a 'Object not valid as React child' error and in the console the object is displayed as <img src='/assets/img/bg1.jpg>
without the closing '/' in the end of the tag.
Our loop to fill the array with Image()
objects looks like this:
for (var i = 1; i <= imgNumber; i++) {
imgArray[i] = new Image()
imgArray[i].src = '/assets/img/bg'+ i +'.jpg'
}