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
- Define two sets of styles with different visual properties (position, opacity, scale, etc.)
- Add
transitionto the element so changes animate - Toggle between class names based on component state
- 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.