React - Simple Animations

Overview

Estimated time: 15–25 minutes

Add micro-interactions using CSS transitions and keyframes for mounting/unmounting and hover effects.

Try it: Fade/slide toggle

View source
function Box(){
  const [open, setOpen] = React.useState(false);
  return (
    <div>
      <button onClick={() => setOpen(o => !o)}>{open? 'Hide' : 'Show'}</button>
      <div className={open? 'panel open' : 'panel'} style={{marginTop:8}}>
        <p>Animated content</p>
      </div>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-anim')).render(<Box />);

Syntax primer

  • Toggle CSS classes to drive transitions.
  • Use keyframes for attention-grabbing effects like a brief hover bounce.

Common pitfalls

  • Avoid animating expensive properties (layout-triggering); prefer transform/opacity.

Exercises

  1. Animate list items entering/leaving with staggered delays.