JavaScript and React course ยท Module 7: Styling and Animations
CSS Animations and Keyframes in React
In this lesson6
Spaceships do not suddenly appear on the radar screen - they fly in, pulse a signal, and smoothly move along their orbit. Animations in web interfaces work on the same principle: they add dynamics to the application and help the user understand what is happening. In this lesson, you will learn techniques for creating CSS animations in React applications - from simple transitions to complex keyframe sequences, and finally we will look at the React Transition Group library.
CSS @keyframes with styled-components
The @keyframes rule allows you to define a sequence of animation steps. In styled-components, we use the keyframes helper, which generates a unique animation name and prevents conflicts:
import styled, { keyframes } from 'styled-components';
// Animation definition - radar signal pulsing
const radarPulse = keyframes`
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.5);
opacity: 0.5;
}
100% {
transform: scale(2);
opacity: 0;
}
`;
const RadarDot = styled.div`
width: 20px;
height: 20px;
border-radius: 50%;
background: #00ff88;
animation: ${radarPulse} 2s ease-out infinite;
`;Key elements:
keyframesis imported fromstyled-components(not from CSS)- Inside we define percentage steps (
0%,50%,100%) or keywords (from,to) - We use interpolation
${radarPulse}in theanimationproperty
You can define any number of keyframes and combine them in different components:
const floatInSpace = keyframes`
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-15px); }
`;
const rotateOrbit = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
const SpaceStation = styled.div`
animation: ${floatInSpace} 4s ease-in-out infinite;
`;
const OrbitRing = styled.div`
animation: ${rotateOrbit} 10s linear infinite;
`;Transition - Smooth State Changes
The transition property in CSS is the simplest way to animate value changes. Instead of defining keyframes, you tell the browser: "when this property changes, do it smoothly." This is the ideal solution for hover effects, clicks, or component state changes.
const NavButton = styled.button`
background: #1a1a3e;
color: #00ff88;
padding: 12px 24px;
border: 2px solid #00ff88;
border-radius: 8px;
cursor: pointer;
/* Define what should be animated and how */
transition: all 0.3s ease;
&:hover {
background: #00ff88;
color: #1a1a3e;
transform: scale(1.05);
box-shadow: 0 0 20px rgba(0, 255, 136, 0.4);
}
`;transition syntax:
transition: property duration timing-function delay;property- what we animate (all,background,transform,opacity...)duration- how long the transition lasts (0.3s,200ms)timing-function- animation curve (ease,linear,ease-in-out,cubic-bezier())delay- start delay (optional)
You can animate multiple properties with different parameters:
const ShipPanel = styled.div`
opacity: 0.8;
transform: translateX(0);
background: #0a0a2e;
transition:
opacity 0.2s ease,
transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94),
background 0.3s ease;
&:hover {
opacity: 1;
transform: translateX(10px);
background: #1a1a4e;
}
`;Animation - Continuous Animations
The animation property is a more advanced version of transition. It allows for continuous, repeating animations, reverse playback, and control over every aspect of movement:
const warningBlink = keyframes`
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
`;
const WarningLight = styled.div`
width: 16px;
height: 16px;
border-radius: 50%;
background: #ff4444;
animation-name: ${warningBlink};
animation-duration: 1s;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
animation-direction: alternate;
`;Or in shorthand form:
animation: name duration timing-function delay iteration-count direction fill-mode;Key parameters:
iteration-count-infinite(endless) or number of repetitions (3)direction-normal,reverse,alternate(back and forth)fill-mode-forwards(keep final state),backwards,bothplay-state-runningorpaused(playback control)
Dynamic Animations Based on Props
In styled-components, you can create animations that respond to component props. This allows dynamically adjusting movement to the application state:
const moveShip = keyframes`
from { transform: translateX(0); }
to { transform: translateX(100%); }
`;
const Spaceship = styled.div`
width: 60px;
height: 30px;
background: #4488ff;
clip-path: polygon(0% 50%, 30% 0%, 100% 50%, 30% 100%);
animation: ${moveShip} ${props => props.speed || 3}s linear infinite;
animation-play-state: ${props => props.isFlying ? 'running' : 'paused'};
opacity: ${props => props.isFlying ? 1 : 0.5};
transition: opacity 0.3s ease;
`;
function FlightControl() {
const [isFlying, setIsFlying] = useState(false);
const [speed, setSpeed] = useState(3);
return (
<div>
<Spaceship isFlying={isFlying} speed={speed} />
<button onClick={() => setIsFlying(!isFlying)}>
{isFlying ? 'Stop' : 'Fly'}
</button>
<input
type="range"
min="0.5"
max="5"
step="0.5"
value={speed}
onChange={(e) => setSpeed(e.target.value)}
/>
<span>Speed: {speed}s per orbit</span>
</div>
);
}You can also dynamically select different keyframes depending on state:
const slideIn = keyframes`
from { transform: translateX(-100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
`;
const slideOut = keyframes`
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(100%); opacity: 0; }
`;
const Panel = styled.div`
animation: ${props => props.isVisible ? slideIn : slideOut} 0.4s ease forwards;
`;This approach allows animating element entry and exit - the panel slides in from the left when appearing and slides out to the right when disappearing.
React Transition Group - CSSTransition
Native CSS cannot animate elements that are added to or removed from the DOM (e.g., through conditional rendering {show && <Component />}). The React Transition Group library solves this problem by managing the enter/exit animation lifecycle.
The most commonly used component is CSSTransition:
import { CSSTransition } from 'react-transition-group';
import { useState, useRef } from 'react';
function NotificationPanel() {
const [showAlert, setShowAlert] = useState(false);
const nodeRef = useRef(null);
return (
<div>
<button onClick={() => setShowAlert(!showAlert)}>
{showAlert ? 'Hide alert' : 'Show alert'}
</button>
<CSSTransition
in={showAlert}
timeout={300}
classNames="alert"
unmountOnExit
nodeRef={nodeRef}
>
<div ref={nodeRef} className="alert-box">
Object detected on radar!
</div>
</CSSTransition>
</div>
);
}CSSTransition automatically adds and removes CSS classes at the appropriate moments:
/* Entry - start */
.alert-enter {
opacity: 0;
transform: translateY(-20px);
}
/* Entry - active phase */
.alert-enter-active {
opacity: 1;
transform: translateY(0);
transition: opacity 300ms ease, transform 300ms ease;
}
/* Exit - start */
.alert-exit {
opacity: 1;
transform: translateY(0);
}
/* Exit - active phase */
.alert-exit-active {
opacity: 0;
transform: translateY(-20px);
transition: opacity 300ms ease, transform 300ms ease;
}Key CSSTransition props:
in- boolean controlling whether the element is visibletimeout- animation duration (in ms), should match the CSS transitionclassNames- CSS class prefix (e.g.,"alert"generatesalert-enter,alert-enter-active, etc.)unmountOnExit- removes the element from DOM after exit animationnodeRef- ref to the animated element (recommended to avoid warnings)
Transition vs Animation - When to Use Which?
Let's summarize when to use each technique:
transition - for simple state changes:
- Hover, focus, active effects
- Color, size, position changes on interaction
- Simple entries/exits (opacity, transform)
@keyframes + animation - for complex and continuous animations:
- Pulsing, rotating, floating
- Multi-step animations (more than 2 states)
- Infinite background or decoration animations
React Transition Group - for component lifecycle animations:
- Animated mounting/unmounting of elements
- Lists with animated adding/removing of elements
- Transitions between views/pages
Well-designed animations are like a ship's navigation system - they guide the user, provide feedback, and make the interface feel natural, like flying through the galaxy with a warp drive, not teleporting without warning.
Code for this lesson: App.jsx
import React, { useState } from 'react';
import styled, { keyframes, css, createGlobalStyle } from 'styled-components';
// ===== GLOBAL STYLES =====
const GlobalStyle = createGlobalStyle`
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', sans-serif;
background: #0a0a1a;
color: #e0e0e0;
}
`;
// ===== KEYFRAME ANIMATIONS =====
// 1. Rotation - ideal for spinners
const spin = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
// 2. Pulsing - heartbeat effect
const pulse = keyframes`
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.05); opacity: 0.8; }
`;
// 3. Floating effect (float)
const float = keyframes`
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-12px); }
`;
// 4. Glowing effect (glow)
const glow = keyframes`
0%, 100% { box-shadow: 0 0 5px rgba(0, 212, 255, 0.3); }
50% { box-shadow: 0 0 25px rgba(0, 212, 255, 0.6), 0 0 50px rgba(0, 212, 255, 0.3); }
`;
// 5. Entrance from the left side
const slideInLeft = keyframes`
from {
opacity: 0;
transform: translateX(-60px);
}
to {
opacity: 1;
transform: translateX(0);
}
`;
// TODO: Create the fadeInUp animation
// The element should appear from the bottom with opacity 0
// from: opacity 0, translateY(30px)
// to: opacity 1, translateY(0)
const fadeInUp = keyframes`
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
`;
// ===== LAYOUT =====
const Container = styled.div`
min-height: 100vh;
padding: 30px;
max-width: 700px;
margin: 0 auto;
`;
const Title = styled.h1`
text-align: center;
color: #00d4ff;
font-size: 2em;
margin-bottom: 5px;
animation: ${float} 3s ease-in-out infinite;
`;
const Subtitle = styled.p`
text-align: center;
color: #778da9;
margin-bottom: 35px;
`;
const Section = styled.div`
margin-bottom: 30px;
animation: ${slideInLeft} 0.6s ease-out;
animation-delay: ${p => p.delay || '0s'};
animation-fill-mode: both;
`;
const SectionTitle = styled.h3`
color: #6c5ce7;
margin-bottom: 15px;
`;
// ===== LOADING SPINNER =====
const SpinnerWrapper = styled.div`
display: flex;
align-items: center;
gap: 15px;
`;
const Spinner = styled.div`
width: 40px;
height: 40px;
border: 3px solid rgba(0, 212, 255, 0.2);
border-top-color: #00d4ff;
border-radius: 50%;
animation: ${spin} 0.8s linear infinite;
`;
// ===== PULSING BUTTON =====
const PulseButton = styled.button`
padding: 12px 28px;
background: #6c5ce7;
color: white;
border: none;
border-radius: 10px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
animation: ${pulse} 2s ease-in-out infinite;
transition: background 0.3s;
&:hover {
background: #5a4bd1;
animation-play-state: paused;
}
`;
// ===== GLOWING CARD =====
const GlowCard = styled.div`
background: rgba(255, 255, 255, 0.04);
border: 1px solid rgba(0, 212, 255, 0.2);
border-radius: 12px;
padding: 24px;
animation: ${glow} 3s ease-in-out infinite;
transition: transform 0.3s;
&:hover {
transform: scale(1.02);
}
h4 {
color: #00d4ff;
margin-bottom: 8px;
}
`;
// ===== ANIMATED CARDS WITH DELAY =====
const StaggerCard = styled.div`
background: rgba(108, 92, 231, 0.1);
border-left: 4px solid #6c5ce7;
border-radius: 8px;
padding: 16px;
margin-bottom: 10px;
animation: ${fadeInUp} 0.5s ease-out both;
animation-delay: ${p => p.delay || '0s'};
`;
// TODO: Create an AnimatedBadge component with conditional animation
// When prop active=true -> pulse animation
// When active=false -> no animation
const AnimatedBadge = styled.span`
display: inline-block;
padding: 4px 14px;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 700;
background: ${p => p.active ? 'rgba(0, 184, 148, 0.2)' : 'rgba(99, 110, 114, 0.2)'};
color: ${p => p.active ? '#00b894' : '#636e72'};
animation: ${p => p.active ? css`${pulse} 2s infinite` : 'none'};
`;
// TODO: Create OrbitDot - a dot orbiting in a circle
// Use @keyframes with transform: rotate() and translateX()
const orbit = keyframes`
from { transform: rotate(0deg) translateX(30px) rotate(0deg); }
to { transform: rotate(360deg) translateX(30px) rotate(-360deg); }
`;
const OrbitContainer = styled.div`
position: relative;
width: 80px;
height: 80px;
display: flex;
align-items: center;
justify-content: center;
`;
const OrbitCenter = styled.div`
width: 16px;
height: 16px;
background: #fdcb6e;
border-radius: 50%;
box-shadow: 0 0 15px rgba(253, 203, 110, 0.5);
`;
const OrbitDot = styled.div`
position: absolute;
width: 8px;
height: 8px;
background: #00d4ff;
border-radius: 50%;
animation: ${orbit} ${p => p.duration || '3s'} linear infinite;
`;
// ===== APPLICATION =====
function App() {
const [showCards, setShowCards] = useState(false);
const missions = [
{ name: 'Mission Alpha', status: true },
{ name: 'Mission Beta', status: true },
{ name: 'Mission Gamma', status: false },
{ name: 'Mission Delta', status: true },
];
return (
<>
<GlobalStyle />
<Container>
<Title>CSS Animations & Keyframes</Title>
<Subtitle>Animations in styled-components</Subtitle>
{/* Section: Spinner */}
<Section delay="0s">
<SectionTitle>Loading Spinner</SectionTitle>
<SpinnerWrapper>
<Spinner />
<span>Scanning space sector...</span>
</SpinnerWrapper>
</Section>
{/* Section: Pulsing button */}
<Section delay="0.15s">
<SectionTitle>Pulsing button</SectionTitle>
<PulseButton onClick={() => setShowCards(!showCards)}>
{showCards ? 'Hide missions' : 'Show missions'}
</PulseButton>
</Section>
{/* Section: Animated cards with delay */}
{showCards && (
<Section delay="0s">
<SectionTitle>Staggered Cards</SectionTitle>
{missions.map((m, i) => (
<StaggerCard key={i} delay={i * 0.12 + 's'}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span>{m.name}</span>
<AnimatedBadge active={m.status}>
{m.status ? 'ACTIVE' : 'OFFLINE'}
</AnimatedBadge>
</div>
</StaggerCard>
))}
</Section>
)}
{/* Section: Glowing card */}
<Section delay="0.3s">
<SectionTitle>Glow Effect</SectionTitle>
<GlowCard>
<h4>Nebula-7 space station</h4>
<p>Card with a pulsing CSS box-shadow glow effect.</p>
</GlowCard>
</Section>
{/* Section: Orbit */}
<Section delay="0.45s">
<SectionTitle>Orbit Animation</SectionTitle>
<div style={{ display: 'flex', alignItems: 'center', gap: 30 }}>
<OrbitContainer>
<OrbitCenter />
<OrbitDot duration="2.5s" />
<OrbitDot duration="4s" />
</OrbitContainer>
<span>Orbit using rotate + translateX</span>
</div>
</Section>
</Container>
</>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Click in order
Arrange the CSS Custom Property definition: