I have a component which takes some state as props and displays in on the screen. I need the fade out the component, then update the state and only then fade it back in. I've seen plenty of examples for specific cases, but not for mine. The catch is that I have multiple buttons which dictate the value shown on the screen. For this matter, I need the value of the clicked button to be passed to useSpring, which I've only found to do this using a unified state object with a temp field.
import React, { useState } from 'react';
import { useSpring, animated } from 'react-spring';
import DisplayComponent from './DisplayComponent';
const FlexRowContainer = () => {
const [state, setState] = useState({ message: 1, temp: 0});
const fadeAnimation = useSpring({
opacity: state.message != state.temp ? 0 : 1,
onRest: () => {
// Check if we're at the end of the fade-out
if (state.message != state.temp) {
// Update the state here to trigger the fade-in next
setState((prev) => ({...prev, message: prev.temp}));
}
},
});
const handleClick = (n: number) => {
// Start the fade-out
setState((prev) => ({...prev, temp: n}));
};
return (
<div>
<button onClick={() => handleClick(1)}>Change number 1</button>
<button onClick={() => handleClick(2)}>Change number 2</button>
<button onClick={() => handleClick(3)}>Change number 3</button>
<animated.div style={fadeAnimation}>
<DisplayComponent state={state} />
</animated.div>
</div>
);
};
export default FlexRowContainer;
The code works perfectly, but I remain curious if there isn't a simpler alternative. I tried building something with useTransition and the reverse field but quickly complicated everything. I'm sure the solution is extremely simple, something like
React spring fade images in/out when prop changes