I have trouble with animating the received prop from the parent component. The animation mechanism I use is Collapse component from material-ui.
When the parent component passes undefined as the text prop, the text disappears immediately and animation "jumps". Look at the code below:
import * as React from "react";
import Switch from "@mui/material/Switch";
import Collapse from "@mui/material/Collapse";
import FormControlLabel from "@mui/material/FormControlLabel";
interface AnimatedTextProps {
text?: string;
}
const AnimatedText = ({ text }: AnimatedTextProps) => (
<div>
<Collapse in={Boolean(text)} timeout={2000} unmountOnExit>
{/* when the parent component passes `undefined` as the text prop, the text disappears immediately */}
{/* it causes that animation "jumps" */}
{/* how to keep the text prop until the animation finishes? */}
<div style={{ background: "red", padding: "40px" }}>{text}</div>
</Collapse>
</div>
);
export default function SimpleCollapse() {
const [text, setText] = React.useState<string | undefined>(undefined);
const handleChange = (e) => {
const checked = e.target.checked;
setText(checked ? "hidden text" : undefined);
};
return (
<div>
<FormControlLabel
control={<Switch checked={Boolean(text)} onChange={handleChange} />}
label="Show"
/>
<AnimatedText text={text} />
</div>
);
}
Sandbox: https://codesandbox.io/s/simplecollapse-material-demo-forked-75tiv?file=/demo.tsx
How to prevent jumping and keep the text prop until the animation finishes?