I have a simple component with some buttons that display text: You click on each different button whenever we want to display different text and I would like to have a simple fade animation when the text switches.
What I am getting instead is a weird overlap between the two states where one appears while the other is disappearing.
This is what my original code looks like within the component:
export default function MyComponent() {
const options = { option1: [OPTION1], option2: [OPTION2], option3: [OPTION3]};
const [selectedOption, setSelectedOption] = React.useState("option1");
return (
<div>
<button onClick={() => setSelectedOption("option1")}>Option 1</button>
<button onClick={() => setSelectedOption("option2")}>Option 2</button>
<button onClick={() => setSelectedOption("option3")}>Option 3</button>
{Object.keys(options).map((option) => (
<CSSTransition
in={option === selectedOption}
key={option}
timeout={1000}
classNames="test"
mountOnEnter
unmountOnExit
>
<div key={option} className="test">
{options[option]}
</div>
</CSSTransition>
))}
</div>
);
}
The alternative way of getting around this is only displaying the {options[option]}
tag within the CSSTransition
component if it is the selectedOption
, basically:
{option === selectedOption && options[option]}
But with that I lose the exit animation before the next one appears. Anyway, all this to say, how could I get a transition out and a transition in smoothly between two states?