React - Transitions
Overview
Estimated time: 10–20 minutes
Use CSS transitions to animate state changes like expanding/collapsing panels and hover effects without extra libraries.
Try it: Expand/Collapse Panel
View source
function ExpandDemo(){
const [open, setOpen] = React.useState(false);
return (
<div>
<button onClick={() => setOpen(o => !o)}>{open ? 'Hide' : 'Show'}</button>
<div className={`panel ${open ? 'expanded' : 'collapsed'}`} style={{marginTop:8}}>
<div className="panel-inner">This content smoothly expands and collapses.</div>
</div>
</div>
);
}
ReactDOM.createRoot(document.getElementById('try-transitions')).render(<ExpandDemo />);
Syntax primer
- Toggle class names in React and define CSS transitions for the affected properties.
Common pitfalls
- Transitioning height:auto doesn’t work; use max-height with an upper bound.
Checks for Understanding
- Why use max-height instead of height:auto for transitions?
- Where do you declare transition properties for React components?
Show answers
- height:auto cannot be animated; max-height can be transitioned to simulate expansion.
- In CSS classes you toggle from React, keeping logic and styling separated.
Exercises
- Add a fade-in transition using opacity for the panel content.
- Make the expanded height responsive by adjusting the max-height class.
- Prevent layout shift by animating padding/margins carefully.