REACT
React Animation: Syntax, Usage, and Examples
React animation enhances user experience by making components move smoothly between states. Whether you're adding subtle transitions or complex animated sequences, React provides multiple ways to integrate animations using CSS, JavaScript, and animation libraries.
How to Implement Animation in React
React animations can be created using CSS transitions, CSS keyframes, JavaScript animations, or animation libraries. Each approach has its strengths, depending on how complex the animation needs to be.
Using CSS Transitions
For simple animations, CSS transitions work well with React. Apply styles dynamically using state.
import React, { useState } from "react";
import "./styles.css"; // External CSS file
function FadeInText() {
const [visible, setVisible] = useState(false);
return (
<div>
<button onClick={() => setVisible(!visible)}>Toggle Text</button>
<p className={visible ? "fade-in" : "fade-out"}>Hello, React Animations!</p>
</div>
);
}
CSS:
.fade-in {
opacity: 1;
transition: opacity 1s ease-in-out;
}
.fade-out {
opacity: 0;
transition: opacity 1s ease-in-out;
}
Using CSS Keyframes
For more complex animations, use keyframes to create smooth transitions between multiple states.
function BouncingBall() {
return (
<div className="ball"></div>
);
}
CSS:
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-20px); }
100% { transform: translateY(0); }
}
.ball {
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
animation: bounce 1s infinite;
}
Using JavaScript for Animation
If you need to control animations with JavaScript, the requestAnimationFrame
API helps create smooth frame-by-frame updates.
import React, { useEffect, useRef } from "react";
function MovingBox() {
const boxRef = useRef(null);
useEffect(() => {
let position = 0;
const animate = () => {
if (boxRef.current) {
position += 2;
boxRef.current.style.transform = `translateX(${position}px)`;
if (position < 200) requestAnimationFrame(animate);
}
};
animate();
}, []);
return <div ref={boxRef} style={{ width: 50, height: 50, background: "blue" }}></div>;
}
When to Use React Animation
Enhancing User Experience
Animations guide users through an interface, making interactions feel more natural. For example, modal windows that fade in and out improve clarity.
Loading and State Changes
React animations help indicate progress or changes in state, such as loading spinners or success messages.
Interactive UI Elements
Hover effects, button clicks, and transitions improve responsiveness and make an app more engaging.
Examples of React Animation
React Animation with Framer Motion
Framer Motion is a powerful animation library for React that simplifies animations with intuitive syntax.
import { motion } from "framer-motion";
function AnimatedBox() {
return (
<motion.div
initial={{ opacity: 0, scale: 0.5 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.5 }}
style={{ width: 100, height: 100, background: "purple" }}
/>
);
}
Animated Page Transitions
For smooth navigation, Framer Motion can animate route changes in React applications.
import { motion } from "framer-motion";
function PageTransition({ children }) {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.5 }}
>
{children}
</motion.div>
);
}
Animated React Native Components
For mobile apps built with React Native, animations make UI transitions fluid.
import { Animated, View } from "react-native";
import { useEffect, useRef } from "react";
function FadeInView({ children }) {
const fadeAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
}).start();
}, []);
return <Animated.View style={{ opacity: fadeAnim }}>{children}</Animated.View>;
}
Learn More About React Animation
Choosing the Right React Animation Library
- Framer Motion – Best for declarative animations and smooth transitions
- React Spring – Useful for physics-based animations
- GSAP (GreenSock) – Great for high-performance animations
- React Transition Group – Ideal for handling component mounting and unmounting
Controlling Animation Performance
For better performance:
- Use
will-change
in CSS to optimize animations - Prefer
transform
andopacity
instead of animating layout properties - Limit the number of re-renders for JavaScript animations
Animating Lists in React
When adding or removing items, animations make lists feel more polished.
import { useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
function AnimatedList() {
const [items, setItems] = useState([1, 2, 3]);
return (
<div>
<button onClick={() => setItems([...items, items.length + 1])}>Add Item</button>
<AnimatePresence>
{items.map((item) => (
<motion.div
key={item}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
>
Item {item}
</motion.div>
))}
</AnimatePresence>
</div>
);
}
Animating Text in React
For typing effects, React Type Animation libraries can create engaging UI elements.
import { TypeAnimation } from "react-type-animation";
function TypingEffect() {
return (
<TypeAnimation
sequence={["Hello, React!", 1000, "React Animations are cool!", 1000]}
wrapper="span"
speed={50}
repeat={Infinity}
/>
);
}
Handling Animation Events
You can trigger functions when animations start or end using event listeners.
function AnimatedButton() {
return (
<motion.button
onAnimationComplete={() => console.log("Animation finished!")}
animate={{ scale: [1, 1.2, 1] }}
transition={{ duration: 0.3 }}
>
Click Me
</motion.button>
);
}
React animation adds life to applications by making UI interactions more fluid. Whether you use CSS, JavaScript, or third-party libraries, choosing the right animation method depends on the complexity of the effect and performance requirements.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.