Cours JavaScript et React · Module 7: Styles et animations

Animations CSS et keyframes dans React

7 min de lecture ·
Dans cette leçon6

Les vaisseaux n'apparaissent pas brusquement sur l'écran radar : ils arrivent en volant, émettent un signal pulsé et se déplacent en douceur le long de leur orbite. Les animations dans les interfaces web fonctionnent selon le même principe : elles ajoutent du dynamisme à l'application et aident l'utilisateur à comprendre ce qui se passe. Dans cette leçon, tu découvriras des techniques pour créer des animations CSS dans les applications React - des simples transitions aux séquences complexes de keyframes, puis nous examinerons la bibliothèque React Transition Group.

CSS @keyframes avec styled-components

La règle @keyframes permet de définir une séquence d'étapes d'animation. Dans styled-components, nous utilisons l'utilitaire keyframes, qui génère un nom d'animation unique et évite les conflits :

import styled, { keyframes } from 'styled-components';

// Définition de l'animation - pulsation du signal radar
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;
`;

Éléments clés :

  • keyframes est importé depuis styled-components (et non depuis le CSS)
  • À l'intérieur, on définit des étapes en pourcentage (0%, 50%, 100%) ou des mots-clés (from, to)
  • On utilise l'interpolation ${radarPulse} dans la propriété animation

Tu peux définir autant de keyframes que tu veux et les combiner dans différents composants :

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 - Changements d'état fluides

La propriété transition en CSS est la façon la plus simple d'animer les changements de valeur. Au lieu de définir des keyframes, tu dis au navigateur : « quand cette propriété change, fais-le en douceur ». C'est la solution idéale pour les effets de survol, les clics ou les changements d'état d'un composant.

const NavButton = styled.button`
  background: #1a1a3e;
  color: #00ff88;
  padding: 12px 24px;
  border: 2px solid #00ff88;
  border-radius: 8px;
  cursor: pointer;

  /* Définir ce qui doit être animé et comment */
  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);
  }
`;

Syntaxe de transition :

transition: property duration timing-function delay;
  • property - ce que l'on anime (all, background, transform, opacity...)
  • duration - combien de temps dure la transition (0.3s, 200ms)
  • timing-function - courbe de l'animation (ease, linear, ease-in-out, cubic-bezier())
  • delay - délai avant le démarrage (optionnel)

Tu peux animer plusieurs propriétés avec des paramètres différents :

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 - Animations continues

La propriété animation est une version plus avancée de transition. Elle permet des animations continues et répétées, une lecture inversée et le contrôle de chaque aspect du mouvement :

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;
`;

Ou sous forme abrégée :

animation: name duration timing-function delay iteration-count direction fill-mode;

Paramètres clés :

  • iteration-count - infinite (sans fin) ou nombre de répétitions (3)
  • direction - normal, reverse, alternate (aller-retour)
  • fill-mode - forwards (conserve l'état final), backwards, both
  • play-state - running ou paused (contrôle de la lecture)

Animations dynamiques basées sur les props

Dans styled-components, tu peux créer des animations qui réagissent aux props du composant. Cela permet d'adapter dynamiquement le mouvement à l'état de l'application :

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 ? 'Arrêter' : 'Voler'}
      </button>

      <input
        type="range"
        min="0.5"
        max="5"
        step="0.5"
        value={speed}
        onChange={(e) => setSpeed(e.target.value)}
      />
      <span>Vitesse : {speed}s par orbite</span>
    </div>
  );
}

Tu peux aussi sélectionner dynamiquement différentes keyframes selon l'état :

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;
`;

Cette approche permet d'animer l'entrée et la sortie d'un élément : le panneau glisse depuis la gauche en apparaissant et glisse vers la droite en disparaissant.

React Transition Group - CSSTransition

Le CSS natif ne peut pas animer les éléments ajoutés ou retirés du DOM (par exemple via le rendu conditionnel {show && <Component />}). La bibliothèque React Transition Group résout ce problème en gérant le cycle de vie de l'animation d'entrée/sortie.

Le composant le plus couramment utilisé est 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 ? "Masquer l'alerte" : "Afficher l'alerte"}
      </button>

      <CSSTransition
        in={showAlert}
        timeout={300}
        classNames="alert"
        unmountOnExit
        nodeRef={nodeRef}
      >
        <div ref={nodeRef} className="alert-box">
          Objet détecté sur le radar !
        </div>
      </CSSTransition>
    </div>
  );
}

CSSTransition ajoute et supprime automatiquement les classes CSS aux moments appropriés :

/* Entrée - début */
.alert-enter {
  opacity: 0;
  transform: translateY(-20px);
}

/* Entrée - phase active */
.alert-enter-active {
  opacity: 1;
  transform: translateY(0);
  transition: opacity 300ms ease, transform 300ms ease;
}

/* Sortie - début */
.alert-exit {
  opacity: 1;
  transform: translateY(0);
}

/* Sortie - phase active */
.alert-exit-active {
  opacity: 0;
  transform: translateY(-20px);
  transition: opacity 300ms ease, transform 300ms ease;
}

Props clés de CSSTransition :

  • in - booléen qui contrôle la visibilité de l'élément
  • timeout - durée de l'animation (en ms), doit correspondre à la transition CSS
  • classNames - préfixe des classes CSS (par exemple "alert" génère alert-enter, alert-enter-active, etc.)
  • unmountOnExit - retire l'élément du DOM après l'animation de sortie
  • nodeRef - ref vers l'élément animé (recommandé pour éviter les avertissements)

Transition vs Animation - Laquelle utiliser ?

Récapitulons quand utiliser chaque technique :

transition - pour les changements d'état simples :

  • Effets de survol, focus, actif
  • Changements de couleur, taille, position lors d'une interaction
  • Entrées/sorties simples (opacity, transform)

@keyframes + animation - pour les animations complexes et continues :

  • Pulsation, rotation, flottement
  • Animations en plusieurs étapes (plus de 2 états)
  • Animations infinies d'arrière-plan ou de décoration

React Transition Group - pour les animations liées au cycle de vie des composants :

  • Montage/démontage animé des éléments
  • Listes avec ajout/suppression animés d'éléments
  • Transitions entre vues/pages

Des animations bien conçues sont comme le système de navigation d'un vaisseau : elles guident l'utilisateur, fournissent un retour d'information et rendent l'interface naturelle, comme traverser la galaxie avec une propulsion à distorsion plutôt que se téléporter sans prévenir.

Code de cette leçon : 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;
  }
`;

// ===== ANIMATIONS KEYFRAMES =====

// 1. Rotation - idéale pour les spinners
const spin = keyframes`
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
`;

// 2. Pulsation - effet de battement de cœur
const pulse = keyframes`
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.05); opacity: 0.8; }
`;

// 3. Effet de flottement (float)
const float = keyframes`
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-12px); }
`;

// 4. Effet de lueur (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. Entrée par la gauche
const slideInLeft = keyframes`
  from {
    opacity: 0;
    transform: translateX(-60px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
`;

// TODO : Crée une animation fadeInUp
// L'élément doit apparaître par le bas avec 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;
`;

// ===== BOUTON PULSANT =====
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;
  }
`;

// ===== CARTE LUMINEUSE =====
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;
  }
`;

// ===== CARTES ANIMÉES AVEC DÉLAI =====
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 : Crée un composant AnimatedBadge avec une animation conditionnelle
// Quand la prop active=true -> animation pulse
// Quand active=false -> aucune 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 : Crée un OrbitDot - un point qui orbite sur un cercle
// Utilise @keyframes avec transform: rotate() et 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 en styled-components</Subtitle>

        {/* Section : Spinner */}
        <Section delay="0s">
          <SectionTitle>Loading Spinner</SectionTitle>
          <SpinnerWrapper>
            <Spinner />
            <span>Analyse du secteur cosmique...</span>
          </SpinnerWrapper>
        </Section>

        {/* Section : Bouton pulsant */}
        <Section delay="0.15s">
          <SectionTitle>Bouton pulsant</SectionTitle>
          <PulseButton onClick={() => setShowCards(!showCards)}>
            {showCards ? 'Hide missions' : 'Show missions'}
          </PulseButton>
        </Section>

        {/* Section : Cartes animées avec délai */}
        {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 : Carte lumineuse */}
        <Section delay="0.3s">
          <SectionTitle>Glow Effect</SectionTitle>
          <GlowCard>
            <h4>Station spatiale Nebula-7</h4>
            <p>Carte avec un effet de lueur pulsante CSS box-shadow.</p>
          </GlowCard>
        </Section>

        {/* Section : Orbite */}
        <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>Orbite avec rotate + translateX</span>
          </div>
        </Section>
      </Container>
    </>
  );
}

export default App;

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Tâches pratiques dans le jeu

  • Clique dans l'ordre

    Ordonne la définition d'une CSS Custom Property :

  1. Clique dans l'ordreBases : Les CSS Custom Properties

Articles utiles