Adding transition Property to React Components
You'll learn how to apply the CSS transition property in React components for smooth, animated property changes.
The Core Idea
The transition property tells the browser to animate changes to specific CSS properties over time, rather than applying them instantly. In React, you apply this just like any other CSS—through className, inline style props, or CSS modules—but you need to trigger the actual property change through state or prop updates.
Think of transition as teaching your component's style to "ease into" changes rather than snap abruptly. When a value shifts (like opacity from 0 to 1), the browser interpolates smoothly over your specified duration.
Three Application Methods
Via className:
/* Button.module.css */
.button {
transition: background-color 0.3s ease;
}
Via inline styles:
<div style={{ transition: 'opacity 0.5s ease-in-out', opacity: isVisible ? 1 : 0 }} />
Via CSS modules with dynamic values:
import styles from './Fade.module.css';
function Fade({ show, children }) {
return (
<div className={styles.fade} style={{ opacity: show ? 1 : 0 }}>
{children}
</div>
);
}
The key: the transition declaration stays constant, but the actual property value (like opacity) changes via React state, triggering the animation.
When Each Method Fits
- className: Best when transitions are fixed design choices
- Inline styles: Useful when duration/easing needs to be dynamic (passed as props)
- CSS modules: Combines scoping benefits with transition declarations
Key Takeaway: The transition property enables smooth animations by declaring which properties should animate and how fast, while React controls when by updating the actual values through state or props.