JavaScript and React course ยท Module 7: Styling and Animations
React Transition Group - Animating Interstellar UI Journeys
In this lesson6
Moving between different states and views in a space application should be as smooth as a spaceship flying through hyperspace. Sudden appearance and disappearance of interface elements feels more like a system failure than a well-designed user experience. In this part of the mission, we will learn about React Transition Group - a library that will help us create smooth, cosmically good transition animations in our interfaces.
What is React Transition Group?
React Transition Group is a low-level API library for component enter/exit animations. Unlike ready-made animation solutions, it does not provide predefined effects - instead, it gives developers full control over the animation process by managing CSS classes or styles at key moments in the component lifecycle.
It is like a spaceship control panel - it does not directly steer the flight, but gives you the tools for precise maneuvering.
Key React Transition Group Components
1. Transition
The basic lower-level component that manages component transition states:
import { Transition } from 'react-transition-group';
import React, { useState } from 'react';
// Styles for different states
const duration = 300;
const defaultStyle = {
transition: `opacity ${duration}ms ease-in-out`,
opacity: 0,
}
const transitionStyles = {
entering: { opacity: 1 },
entered: { opacity: 1 },
exiting: { opacity: 0 },
exited: { opacity: 0 },
};
function FadeExample() {
const [inProp, setInProp] = useState(false);
return (
<div>
<button onClick={() => setInProp(!inProp)}>
{inProp ? 'Disappear' : 'Appear'}
</button>
<Transition in={inProp} timeout={duration}>
{state => (
<div style={{
...defaultStyle,
...transitionStyles[state]
}}>
Message from space
</div>
)}
</Transition>
</div>
);
}2. CSSTransition
Extends Transition with automatic adding/removing of CSS classes, making it easier to create animations:
import { CSSTransition } from 'react-transition-group';
import React, { useState } from 'react';
import './styles.css';
function AlertExample() {
const [showAlert, setShowAlert] = useState(false);
return (
<div>
<button onClick={() => setShowAlert(prev => !prev)}>
{showAlert ? 'Hide alert' : 'Show alert'}
</button>
<CSSTransition
in={showAlert}
timeout={300}
classNames="alert"
unmountOnExit
>
<div className="alert">
<h4>Message from headquarters!</h4>
<p>A new planet suitable for colonization has been detected.</p>
</div>
</CSSTransition>
</div>
);
}And in the CSS file:
/* styles.css */
.alert {
background-color: #121a2b;
color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 20px rgba(82, 161, 255, 0.5);
margin-top: 20px;
}
.alert-enter {
opacity: 0;
transform: scale(0.9);
}
.alert-enter-active {
opacity: 1;
transform: scale(1);
transition: opacity 300ms, transform 300ms;
}
.alert-exit {
opacity: 1;
transform: scale(1);
}
.alert-exit-active {
opacity: 0;
transform: scale(0.9);
transition: opacity 300ms, transform 300ms;
}3. TransitionGroup
Manages a collection of Transition or CSSTransition components, ideal for animating lists:
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import React, { useState } from 'react';
import './styles.css';
function StarsList() {
const [items, setItems] = useState([
{ id: 1, name: 'Alpha Centauri' },
{ id: 2, name: 'Proxima Centauri' },
{ id: 3, name: 'Betelgeuse' }
]);
const [nextId, setNextId] = useState(4);
const addStar = () => {
const newStars = [
'Sirius', 'Vega', 'Polaris', 'Canopus', 'Arcturus',
'Antares', 'Rigel', 'Procyon', 'Deneb'
];
const randomStar = newStars[Math.floor(Math.random() * newStars.length)];
setItems([...items, { id: nextId, name: randomStar }]);
setNextId(nextId + 1);
};
const removeStar = id => {
setItems(items.filter(item => item.id !== id));
};
return (
<div>
<h2>Stars to visit</h2>
<button onClick={addStar}>Add star</button>
<TransitionGroup className="stars-list">
{items.map(({ id, name }) => (
<CSSTransition
key={id}
timeout={500}
classNames="star-item"
>
<div className="star-item">
<span>{name}</span>
<button onClick={() => removeStar(id)}>
×
</button>
</div>
</CSSTransition>
))}
</TransitionGroup>
</div>
);
}CSS for this example:
/* styles.css */
.stars-list {
margin-top: 20px;
}
.star-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 20px;
margin-bottom: 10px;
background-color: #0d1b2a;
border-radius: 8px;
color: #e0f7fa;
border-left: 4px solid #4fc3f7;
}
.star-item-enter {
opacity: 0;
transform: translateX(-30px);
}
.star-item-enter-active {
opacity: 1;
transform: translateX(0);
transition: opacity 500ms, transform 500ms;
}
.star-item-exit {
opacity: 1;
}
.star-item-exit-active {
opacity: 0;
transform: translateX(30px);
transition: opacity 500ms, transform 500ms;
}Advanced Techniques
1. Sequential Animations
Animating elements one after another for a cascading effect:
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import React, { useState, useEffect } from 'react';
import './styles.css';
function LaunchSequence() {
const [steps, setSteps] = useState([]);
const allSteps = [
{ id: 1, text: "Starting systems" },
{ id: 2, text: "Main engine check" },
{ id: 3, text: "Checking navigation systems" },
{ id: 4, text: "Sealing hatches" },
{ id: 5, text: "Countdown to launch" }
];
useEffect(() => {
if (steps.length < allSteps.length) {
const timer = setTimeout(() => {
setSteps(prevSteps => [
...prevSteps,
allSteps[prevSteps.length]
]);
}, 1000);
return () => clearTimeout(timer);
}
}, [steps]);
return (
<div className="launch-sequence">
<h2>Launch Sequence</h2>
<TransitionGroup>
{steps.map(step => (
<CSSTransition
key={step.id}
timeout={500}
classNames="launch-step"
>
<div className="launch-step">
<div className="step-number">{step.id}</div>
<div className="step-text">{step.text}</div>
</div>
</CSSTransition>
))}
</TransitionGroup>
</div>
);
}2. Animation Choreography
Synchronizing multiple animations to create complex sequences:
import { Transition } from 'react-transition-group';
import React, { useState } from 'react';
function SpaceshipDashboard() {
const [active, setActive] = useState(false);
// Durations for different elements
const durations = {
background: 500,
systems: 400,
controls: 600,
status: 700,
};
// Styles for different states
const getStyles = (elementName, state) => {
const baseStyles = {
transition: `all ${durations[elementName]}ms ease-out`,
};
const elementSpecificStyles = {
background: {
entering: { opacity: 1, filter: 'brightness(1)' },
entered: { opacity: 1, filter: 'brightness(1)' },
exiting: { opacity: 0.5, filter: 'brightness(0.4)' },
exited: { opacity: 0.5, filter: 'brightness(0.4)' },
},
systems: {
entering: { opacity: 1, transform: 'translateY(0)' },
entered: { opacity: 1, transform: 'translateY(0)' },
exiting: { opacity: 0, transform: 'translateY(20px)' },
exited: { opacity: 0, transform: 'translateY(20px)' },
},
controls: {
entering: { opacity: 1, transform: 'scale(1)' },
entered: { opacity: 1, transform: 'scale(1)' },
exiting: { opacity: 0, transform: 'scale(0.8)' },
exited: { opacity: 0, transform: 'scale(0.8)' },
},
status: {
entering: { opacity: 1, transform: 'translateX(0)' },
entered: { opacity: 1, transform: 'translateX(0)' },
exiting: { opacity: 0, transform: 'translateX(-20px)' },
exited: { opacity: 0, transform: 'translateX(-20px)' },
},
};
return {
...baseStyles,
...elementSpecificStyles[elementName][state],
};
};
// Initial styles for elements
const initialStyles = {
background: { opacity: 0.5, filter: 'brightness(0.4)' },
systems: { opacity: 0, transform: 'translateY(20px)' },
controls: { opacity: 0, transform: 'scale(0.8)' },
status: { opacity: 0, transform: 'translateX(-20px)' },
};
return (
<div className="dashboard-container">
<button onClick={() => setActive(!active)}>
{active ? 'Shut down systems' : 'Start systems'}
</button>
<div className="spaceship-dashboard">
<Transition in={active} timeout={durations.background}>
{state => (
<div
className="dashboard-background"
style={{
...initialStyles.background,
...getStyles('background', state)
}}
/>
)}
</Transition>
<Transition in={active} timeout={durations.systems}>
{state => (
<div
className="system-panels"
style={{
...initialStyles.systems,
...getStyles('systems', state)
}}
>
System Diagnostics
</div>
)}
</Transition>
<Transition in={active} timeout={durations.controls}>
{state => (
<div
className="control-panels"
style={{
...initialStyles.controls,
...getStyles('controls', state)
}}
>
Flight Controls
</div>
)}
</Transition>
<Transition in={active} timeout={durations.status}>
{state => (
<div
className="status-panels"
style={{
...initialStyles.status,
...getStyles('status', state)
}}
>
Status Monitors
</div>
)}
</Transition>
</div>
</div>
);
}Best Practices for Cosmically Smooth Animations
Avoid animating computationally expensive properties - properties like
width,height, andtopcan cause reflow. Prefertransformandopacity.Use animation debuggers - tools like Chrome DevTools allow you to analyze animation performance.
Think through start and end points - a well-designed animation has clearly defined states.
Do not overdo the duration - animations should be short enough not to delay user interaction (usually 150-500ms).
Add delays for complex sequences - use
delayto create cascading effects.Ensure accessibility - remember users who may prefer reduced animations (
prefers-reduced-motion).
Example: Interstellar Portal
Let's create a portal component that animates the transition between "worlds" (views) in our cosmic application:
import { CSSTransition } from 'react-transition-group';
import React, { useState } from 'react';
import './portal.css';
function InterstellarPortal({ children, show, onExited }) {
return (
<CSSTransition
in={show}
timeout={1000}
classNames="portal"
unmountOnExit
onExited={onExited}
>
<div className="portal-container">
<div className="portal-content">
{children}
</div>
</div>
</CSSTransition>
);
}
function App() {
const [currentWorld, setCurrentWorld] = useState('home');
const [showPortal, setShowPortal] = useState(true);
const [nextWorld, setNextWorld] = useState(null);
const worlds = {
home: {
title: "Space Station Alpha",
content: "Welcome aboard Space Station Alpha, the command center of our interstellar operation."
},
mars: {
title: "Mars Colony One",
content: "Welcome to the first colony on Mars. Terraforming work is in progress."
},
europa: {
title: "Underwater Base Europa",
content: "Welcome to the research base beneath the icy shell of Jupiter's moon - Europa."
}
};
const navigateTo = (world) => {
setNextWorld(world);
setShowPortal(false);
};
const onPortalExited = () => {
setCurrentWorld(nextWorld);
setShowPortal(true);
};
return (
<div className="app">
<nav className="navigation">
<button onClick={() => navigateTo('home')} disabled={currentWorld === 'home'}>
Station Alpha
</button>
<button onClick={() => navigateTo('mars')} disabled={currentWorld === 'mars'}>
Mars
</button>
<button onClick={() => navigateTo('europa')} disabled={currentWorld === 'europa'}>
Europa
</button>
</nav>
<InterstellarPortal show={showPortal} onExited={onPortalExited}>
<h1>{worlds[currentWorld].title}</h1>
<p>{worlds[currentWorld].content}</p>
</InterstellarPortal>
</div>
);
}CSS for the portal:
/* portal.css */
.portal-container {
position: relative;
overflow: hidden;
min-height: 300px;
padding: 30px;
background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}
.portal-content {
background: rgba(0, 0, 0, 0.7);
padding: 30px;
border-radius: 8px;
color: white;
}
/* Entry animation */
.portal-enter {
opacity: 0;
transform: scale(0.7);
}
.portal-enter-active {
opacity: 1;
transform: scale(1);
transition: opacity 1000ms ease-out, transform 1000ms cubic-bezier(0.34, 1.56, 0.64, 1);
}
/* Exit animation */
.portal-exit {
opacity: 1;
transform: scale(1);
}
.portal-exit-active {
opacity: 0;
transform: scale(1.3);
transition: opacity 1000ms ease-in, transform 1000ms cubic-bezier(0.36, 0, 0.66, -0.56);
}
/* Navigation style */
.navigation {
display: flex;
justify-content: center;
gap: 15px;
margin-bottom: 30px;
}
.navigation button {
background-color: #2c3e50;
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
}
.navigation button:hover:not(:disabled) {
background-color: #34495e;
transform: translateY(-2px);
}
.navigation button:disabled {
background-color: #95a5a6;
cursor: not-allowed;
}Practical Exercise: Create an Animated Planet Gallery
Design and implement an animated gallery of planets in our solar system. When a user navigates between planets, use React Transition Group to create smooth transitions between views. For each planet display:
- Planet name
- Planet image
- A few key facts (size, distance from the Sun, temperature)
Add the following animations:
- Smooth transition between planets
- Cascading effect for displaying planet facts
- A "Back to overview" button with a transition animation
Remember that good animation enhances the user experience, not distracts from it. Animations should be smooth and natural, like the journey through space itself - elegant, majestic, and inspiring.
Code for this lesson: App.jsx
import React, { useState, useRef } from 'react';
import './styles.css';
// ===== SIMULATING REACT TRANSITION GROUP =====
// Sandpack doesn't support react-transition-group,
// so we implement CSS animations with transition classes
// CSSTransition component - simplified version
function CSSTransition({ inProp, timeout, children, classNames, unmountOnExit }) {
const [mounted, setMounted] = React.useState(inProp);
const [animClass, setAnimClass] = React.useState('');
React.useEffect(() => {
if (inProp) {
setMounted(true);
setAnimClass(classNames + '-enter');
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setAnimClass(classNames + '-enter-active');
});
});
} else {
setAnimClass(classNames + '-exit');
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setAnimClass(classNames + '-exit-active');
});
});
const timer = setTimeout(() => {
if (unmountOnExit) setMounted(false);
}, timeout);
return () => clearTimeout(timer);
}
}, [inProp]);
if (!mounted && unmountOnExit) return null;
return (
<div className={animClass}>
{children}
</div>
);
}
// ===== DEMO 1: Fade In/Out =====
function FadeDemo() {
const [show, setShow] = useState(false);
return (
<div className="demo-section">
<h3>Fade In / Out</h3>
<button
className="demo-btn"
onClick={() => setShow(!show)}
>
{show ? 'Hide' : 'Show'} message
</button>
<CSSTransition
inProp={show}
timeout={400}
classNames="fade"
unmountOnExit
>
<div className="alert-box">
Detected a new planet suitable for colonization!
</div>
</CSSTransition>
</div>
);
}
// ===== DEMO 2: Animated List =====
function AnimatedList() {
const [items, setItems] = useState([
{ id: 1, name: 'Alpha Centauri', visible: true },
{ id: 2, name: 'Proxima Centauri', visible: true },
{ id: 3, name: 'Betelgeuse', visible: true },
]);
const nextId = useRef(4);
const starNames = [
'Sirius', 'Vega', 'Polaris', 'Canopus',
'Arcturus', 'Antares', 'Rigel', 'Procyon',
];
const addStar = () => {
const name = starNames[Math.floor(Math.random() * starNames.length)];
const newItem = { id: nextId.current++, name, visible: false };
setItems(prev => [...prev, newItem]);
// Run enter animation after mounting
setTimeout(() => {
setItems(prev =>
prev.map(item =>
item.id === newItem.id ? { ...item, visible: true } : item
)
);
}, 50);
};
const removeStar = (id) => {
// First trigger the exit animation
setItems(prev =>
prev.map(item =>
item.id === id ? { ...item, visible: false } : item
)
);
// Then remove the element
setTimeout(() => {
setItems(prev => prev.filter(item => item.id !== id));
}, 500);
};
return (
<div className="demo-section">
<h3>Animated star list</h3>
<button className="demo-btn" onClick={addStar}>
+ Add star
</button>
<div className="star-list">
{items.map(item => (
<div
key={item.id}
className={"star-item " + (item.visible ? 'star-item-enter-active' : 'star-item-exit-active')}
>
<span>{item.name}</span>
<button
className="remove-btn"
onClick={() => removeStar(item.id)}
>
ร
</button>
</div>
))}
</div>
</div>
);
}
// TODO: Create a SlideDemo component with a slide animation
// The component should:
// 1. Have a button to toggle visibility
// 2. Animate the element with a translation from the top (translateY)
// 3. Use the CSS classes: slide-enter, slide-enter-active, slide-exit-active
function SlideDemo() {
const [show, setShow] = useState(false);
return (
<div className="demo-section">
<h3>Slide Transition</h3>
<button className="demo-btn" onClick={() => setShow(!show)}>
{show ? 'Collapse' : 'Expand'} panel
</button>
{/* TODO: Add an animated panel with the slide class */}
{/* Use CSSTransition or manual class logic */}
<CSSTransition
inProp={show}
timeout={400}
classNames="slide"
unmountOnExit
>
<div className="slide-panel">
<h4>Mission control panel</h4>
<p>Engine status: ONLINE</p>
<p>Course: Alpha Centauri</p>
<p>ETA: 4.37 light years</p>
</div>
</CSSTransition>
</div>
);
}
// ===== MAIN APPLICATION =====
function App() {
return (
<div className="app-container">
<h1 className="app-title">React Transition Group</h1>
<p className="app-subtitle">Transition animations in a space application</p>
<FadeDemo />
<AnimatedList />
<SlideDemo />
</div>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Vertical ordering
Order the steps for adding CSS animations to a React component: