I have a React component that dynamically renders slides on the page from a slides object based on a state variable. I'd like to add some CSS transitions when the slides enter and exit, but I can't seem to find a good way to do it. Below is a simplified example of what I'm working with, but should get the idea across:
const slides = {
slide1: {
id: 1,
content: <>Slide content</>,
nextSlide: slide2,
prevSlide: null
},
slide2: {
id: 2,
content: <>Slide content</>,
nextSlide: slide3,
prevSlide: slide1,
},
slide3: {
id: 3,
content: <>Slide content</>,
nextSlide: null,
prevSlide: slide2
}
}
const [currentSlide, setCurrentSlide] = useState("slide1")
return (
<div>
{slides[currentSlide].content}
<button onClick={() => setCurrentSlide(slides[currentSlide].prevSlide}
Previous Slide
</button>
<button onClick={() => setCurrentSlide(slides[currentSlide].nextSlide}
Next Slide
</button>
</div>
)
I've tried writing a handler function that sets the slide state change on a delay and then triggers a separate state variable that inject a CSS class name corresponding to some transition rules into the content container, but I couldn't get it working how I thought it would. What's the best way to do this?