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

  1. Why use max-height instead of height:auto for transitions?
  2. Where do you declare transition properties for React components?
Show answers
  1. height:auto cannot be animated; max-height can be transitioned to simulate expansion.
  2. In CSS classes you toggle from React, keeping logic and styling separated.

Exercises

  1. Add a fade-in transition using opacity for the panel content.
  2. Make the expanded height responsive by adjusting the max-height class.
  3. Prevent layout shift by animating padding/margins carefully.