Course contentsShow
← React
Lesson 1959 of 2,39645. AnimationsFree lesson

Animating State-Driven Classes

Toggle classes based on component state to trigger CSS transitions between visual states.

Animating State-Driven Classes

You'll learn how to smoothly animate between visual states by toggling CSS classes in response to component state changes.

The Core Pattern

You've already added transition properties to your components. Now you'll make those transitions do something by changing classes when state changes. The browser automatically animates the differences.

Think of it like a light switch with a dimmer: flipping the switch (state change) triggers the dimmer (CSS transition) to smoothly fade between off and on states.

How It Works

  1. Define two sets of styles with different visual properties (position, opacity, scale, etc.)
  2. Add transition to the element so changes animate
  3. Toggle between class names based on component state
  4. CSS automatically interpolates between the old and new values

Basic Example

/* styles.module.css */
.box {
  width: 100px;
  height: 100px;
  background: blue;
  transition: all 0.3s ease;
}

.expanded {
  width: 200px;
  background: purple;
}
function AnimatedBox() {
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    <div 
      className={isExpanded ? 'box expanded' : 'box'}
      onClick={() => setIsExpanded(!isExpanded)}
    >
      Click me
    </div>
  );
}

When isExpanded flips to true, the browser sees the new width and background values and smoothly animates from the old values to the new ones over 0.3 seconds.

With Utility Libraries

Using clsx keeps conditional class logic clean:

className={clsx(styles.box, {
  [styles.expanded]: isExpanded,
  [styles.collapsed]: !isExpanded
})}

Key Takeaway: State-driven class toggling combined with CSS transitions creates smooth animations without JavaScript animation libraries—the browser handles all interpolation automatically.