CSS Keyframe Animations in React
How to use @keyframes animations in React — styled-components, CSS Modules, and Framer Motion comparison.
Published:
Tags: CSS animations React, React animation CSS keyframes, Framer Motion vs CSS animation
CSS Keyframe Animations in React animations work in React exactly as they do in plain HTML — the mechanism is pure CSS. The main question is where to define the keyframe block based on your project's styling approach. --- What is approach 1: global css or css file? The simplest approach. Define in a file imported at the root or component level. --- What is Approach 2: CSS Modules? Keyframe blocks in CSS Modules are locally scoped. The animation name gets the same unique hash as class names. --- What is approach 3: styled-components helper? styled-components provides a tagged template literal that handles scoping and typing: --- What is Approach 4: Framer Motion? Framer Motion replaces with a declarative prop on components. It also handles exit animations (when components unmount), which…
Frequently Asked Questions
How do I add CSS animations to React?
Define `@keyframes` in a CSS file or CSS Module, then apply the `animation` property via a class name on the JSX element. For CSS Modules, import the styles object and use `className={styles.animated}`. For styled-components, use the `keyframes` helper from the library to create typed keyframe blocks.
What is the best animation library for React?
Framer Motion is the most capable and developer-friendly library for complex React animations — it handles layout animations, shared element transitions, and gesture-based motion. For simple entrance/exit animations, CSS `@keyframes` with a class toggle is sufficient and adds zero bundle cost. React Spring is a strong middle-ground for physics-based motion.
How do I use @keyframes in styled-components?
Import `keyframes` from styled-components: `import styled, { keyframes } from 'styled-components'`. Define the animation: `const fadeIn = keyframes\`from { opacity: 0 } to { opacity: 1 }\``. Then reference it in a styled component: `animation: ${fadeIn} 0.3s ease both`.
How do I add entrance animations in React?
The simplest approach: define a `@keyframes fadeInUp` animation, add the animation class to elements as they render. For conditional entrance (component mounts), the CSS animation runs automatically on mount. For scroll-triggered entrances, use an `IntersectionObserver` to add the animation class when the element enters the viewport.
What is Framer Motion?
Framer Motion is a React animation library that uses declarative `motion` components and `animate`/`initial`/`exit` props instead of CSS keyframes. It handles complex scenarios like layout transitions, shared element animations, and exit animations (which CSS alone cannot handle for unmounting components) via an `AnimatePresence` wrapper.
All articles · theproductguy.in