-1

the below code the transition or animation is not working but the image is just changing.

styles : {
   imageStyle : {
      opacity:1,
      transition:"opacity 0.5s linear",
      height: "304px",
      width: "622px",
    }
}


const imageBox =() =>{
  const images = [ "one.jpeg", "two.jpeg", "three.jpeg", "four.jpeg" ];
  const [currentIndex, setCurrentIndex] = useState(0);

  return
   <>
      <img style={styles.imageStyle} src={images[currentIndex]} >
      <button onclick={()=>setCurrentIndex(prevState => prevState + 1)}>next image</button>
   <>

}

shafa vp
  • 89
  • 7
  • 1
    Does this work in regular HTML/CSS? I don't think this is a React issue, you just can't animate an image src changing. Have a look at: https://stackoverflow.com/questions/23583245/add-transition-while-changing-img-src-with-javascript – DBS Jul 19 '23 at 08:53
  • If you want a transition of the opacity, then the opacity value of the element must actually change. Just setting a new image src, does nothing regarding the opacity. – CBroe Jul 19 '23 at 09:04

1 Answers1

1

You can use react-transition-group

import { useState } from "react";
import "./styles.css";
import { TransitionGroup, CSSTransition } from "react-transition-group";

export default function App() {
  const images = [
    "https://images.pexels.com/photos/17645273/pexels-photo-17645273/free-photo-of-mode-gens-femme-detente.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "https://images.pexels.com/photos/17427998/pexels-photo-17427998/free-photo-of-printemps-a-val-gardena.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "https://images.pexels.com/photos/6142740/pexels-photo-6142740.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "https://images.pexels.com/photos/17494608/pexels-photo-17494608/free-photo-of-mer-plage-vacances-eau.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
  ];
  const [currentIndex, setCurrentIndex] = useState(0);

  const styles = {
    imageStyle: {
      opacity: 1,
      transition: "opacity 0.5s linear",
      height: "304px",
      width: "422px"
    }
  };

  const handleImageChange = () => {
    if (images.length === currentIndex + 1) {
      setCurrentIndex(0);
    } else {
      setCurrentIndex((prevState) => prevState + 1);
    }
  };

  return (
    <div className="App">
      <h1>Image Slider {currentIndex}</h1>
      <TransitionGroup>
        <CSSTransition key={images[currentIndex]} timeout={1000}>
          <img
            style={styles.imageStyle}
            alt="Slider"
            src={images[currentIndex]}
            className="animate"
          />
        </CSSTransition>
      </TransitionGroup>
      <button onClick={() => handleImageChange()}>next image</button>
    </div>
  );
}

https://codesandbox.io/s/beautiful-torvalds-8ghnjw?file=/src/App.js:0-1645