Search code examples
cssreactjscss-animationsbackground-image

Create fade in/out animation on background images change css in react


I create a list of images and every 5 seconds the image displayed as the background image is changed to the next. when changing from one image to another I want the image to be replaced to fade out in like 0.2s and the image be displayed to fade in 0.2s.

here is what i did in my component :

export default function Login() {
  const Images = [ ...someImagesLinks ]
  const [position, setPosition] = useState(0);
  useEffect(() => {
    const interval = setInterval(() => {
      if (position === 3) setPosition(0);
      else setPosition(position + 1);
    }, 5000);
    return () => clearInterval(interval);
  }, [position]);

  return (
    <div className="loginPageContainer">
      <div
        style={{url("${Images[position].img}")`}}
        className="bg_images_login"
      >
      </div>
    </div>
  );
}

and here's my css :

.bg_images_login {
  width: 100vw;
  height: 100vh;
  margin: 0;
 }

the images change every 5 seconds but with no animation. how can I solve this issue with CSS?


Solution

  • if you don't mind adding more dependencies, take a look at this : React Spring
    here is the direct link to the IMAGE FADE demo