I created a layerd image in Photoshop. I would like to add one layer of that image to the background of a div every second. This is the code I am currently working with, but it's not working. Any help is appreaciated.
import React, { useRef, useEffect } from 'react';
import img1 from '../../img/INTRO/1.png';
import img2 from '../../img/INTRO/2.png';
import img2 from '../../img/INTRO/3.png';
function IntroMain() {
const imageDiv = useRef();
useEffect(() => {
let arrOfImages = new Array(),
i = 0,
interval = 700,
currentBG;
window.setTimeout(() => {
console.log('set bg img now');
imageDiv.current.style.backgroundImage = `url(${img3})`;
imageDiv.current.style.backgroundSize = `cover`;
currentBG = `url(${img1}), `;
}, interval);
window.setTimeout(() => {
console.log('set bg 2 img now');
imageDiv.current.style.backgroundImage = `url(${img2})`;
imageDiv.current.style.backgroundSize = `cover, cover`;
}, interval * 2);
});
return <div id="image-div" ref={imageDiv}></div>;
}
export default IntroMain;
For setting multiple background images on a div
you can use the css property background-image
. It looks like:
background-image: url('/first/image.jpg'), url('second/image.jpg') ...;
Your app can hold the image urls and the display state in an array that you can update through user interaction or based on time. You can then dynamically build the css property value from the image urls to display. Example App:
const IMAGES = [
// this could be real paths instead
/* red */ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
/* green */ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
/* blue */ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
];
const Toggle = ({ layers, onToggle }) => {
// this component is just for demonstration of dynamically toggling images
return layers.map((layer, idx) => (
<button
key={layer.url}
onClick={() => onToggle(idx)}
style={{ background: layer.display ? `url(${layer.url})` : "none" }}
>{`Toggle Layer ${idx}`}</button>
));
};
const Layers = () => {
// we initialize the array from the image urls and set every layer to display: false
const [layers, setLayers] = useState(() =>
IMAGES.map(url => ({ url, display: false }))
);
// this method toggles the display state of the layer at idx
const handleToggleLayer = idx =>
setLayers(current =>
current.map((layer, i) =>
i === idx ? { ...layer, display: !layer.display } : layer
)
);
return (
<div>
<Toggle layers={layers} onToggle={handleToggleLayer} />
<div
className="layers"
style={{
backgroundImage: layers
.filter(layer => layer.display)
.map(layer => `url(${layer.url})`)
.join(", ")
}}
/>
</div>
);
};
Live Demo:
Note that the first image listed will be on top (the front-most).
The example uses template strings to wrap the image paths in url( ... )
and .join()
to join them.