Kurs JavaScript i React · Moduł 7: Stylowanie i animacje

Animacje CSS i keyframes w React

6 min czytania ·
W tej lekcji6

Statki kosmiczne nie pojawiają się nagle na ekranie radaru - wlatują, pulsują sygnałem, płynnie przesuwają się po orbicie. Animacje w interfejsach webowych działają na tej samej zasadzie: nadają aplikacji dynamiki i pomagają użytkownikowi zrozumieć, co się dzieje. W tej lekcji poznasz techniki tworzenia animacji CSS w aplikacjach React - od prostych przejść po złożone sekwencje z keyframes, a na końcu zajrzymy do biblioteki React Transition Group.

CSS @keyframes z styled-components

Reguła @keyframes pozwala zdefiniować sekwencję kroków animacji. W styled-components korzystamy z helpera keyframes, który generuje unikalną nazwę animacji i zapobiega konfliktom:

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

// Definicja animacji - pulsowanie sygnału radarowego
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;
`;

Kluczowe elementy:

  • keyframes importujemy z styled-components (nie z CSS)
  • Wewnątrz definiujemy kroki procentowe (0%, 50%, 100%) lub słowa kluczowe (from, to)
  • Używamy interpolacji ${radarPulse} w propercie animation

Możesz definiować dowolnie wiele keyframes i łączyć je w różnych komponentach:

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 - płynne przejścia stanów

Właściwość transition w CSS to najprostszy sposób na animowanie zmian wartości. Zamiast definiować keyframes, mówisz przeglądarce: "gdy ta właściwość się zmieni, zrób to płynnie". To idealne rozwiązanie dla efektów hover, kliknięcia czy zmiany stanu komponentu.

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

  /* Definiujemy, co ma być animowane i jak */
  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);
  }
`;

Składnia transition:

transition: property duration timing-function delay;
  • property - co animujemy (all, background, transform, opacity...)
  • duration - jak długo trwa przejście (0.3s, 200ms)
  • timing-function - krzywa animacji (ease, linear, ease-in-out, cubic-bezier())
  • delay - opóźnienie startu (opcjonalne)

Możesz animować wiele właściwości z różnymi parametrami:

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 - ciągłe animacje

Właściwość animation to bardziej zaawansowana wersja transition. Pozwala na ciągłe, powtarzające się animacje, odtwarzanie wstecz i kontrolę nad każdym aspektem ruchu:

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

Albo w skróconej formie:

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

Najważniejsze parametry:

  • iteration-count - infinite (nieskończone) lub liczba powtórzeń (3)
  • direction - normal, reverse, alternate (tam i z powrotem)
  • fill-mode - forwards (zachowaj stan końcowy), backwards, both
  • play-state - running lub paused (kontrola odtwarzania)

Dynamiczne animacje oparte na props

W styled-components możesz tworzyć animacje, które reagują na props komponentu. To pozwala na dynamiczne dostosowanie ruchu do stanu aplikacji:

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 ? 'Zatrzymaj' : 'Leć'}
      </button>

      <input
        type="range"
        min="0.5"
        max="5"
        step="0.5"
        value={speed}
        onChange={(e) => setSpeed(e.target.value)}
      />
      <span>Prędkość: {speed}s na okrążenie</span>
    </div>
  );
}

Możesz też dynamicznie wybierać różne keyframes w zależności od stanu:

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

To podejście pozwala na animowanie wejścia i wyjścia elementów - panel wsuwa się z lewej strony przy pojawieniu i wysuwa w prawo przy znikaniu.

React Transition Group - CSSTransition

Natywne CSS nie potrafi animować elementów, które są dodawane lub usuwane z DOM (np. przez warunkowe renderowanie {show && <Component />}). Biblioteka React Transition Group rozwiązuje ten problem, zarządzając cyklem życia animacji wejścia/wyjścia.

Najczęściej używany komponent to 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 ? 'Ukryj alert' : 'Pokaż alert'}
      </button>

      <CSSTransition
        in={showAlert}
        timeout={300}
        classNames="alert"
        unmountOnExit
        nodeRef={nodeRef}
      >
        <div ref={nodeRef} className="alert-box">
          Wykryto obiekt na radarze!
        </div>
      </CSSTransition>
    </div>
  );
}

CSSTransition automatycznie dodaje i usuwa klasy CSS w odpowiednich momentach:

/* Wejście - start */
.alert-enter {
  opacity: 0;
  transform: translateY(-20px);
}

/* Wejście - aktywna faza */
.alert-enter-active {
  opacity: 1;
  transform: translateY(0);
  transition: opacity 300ms ease, transform 300ms ease;
}

/* Wyjście - start */
.alert-exit {
  opacity: 1;
  transform: translateY(0);
}

/* Wyjście - aktywna faza */
.alert-exit-active {
  opacity: 0;
  transform: translateY(-20px);
  transition: opacity 300ms ease, transform 300ms ease;
}

Kluczowe propsy CSSTransition:

  • in - boolean kontrolujący, czy element jest widoczny
  • timeout - czas trwania animacji (w ms), powinien odpowiadać CSS transition
  • classNames - prefiks klas CSS (np. "alert" generuje alert-enter, alert-enter-active itd.)
  • unmountOnExit - usuwa element z DOM po animacji wyjścia
  • nodeRef - ref do animowanego elementu (zalecane dla uniknięcia ostrzeżeń)

Transition vs Animation - kiedy co wybrać?

Podsumujmy, kiedy używać poszczególnych technik:

transition - dla prostych zmian stanów:

  • Efekty hover, focus, active
  • Zmiana koloru, rozmiaru, pozycji przy interakcji
  • Proste wejścia/wyjścia (opacity, transform)

@keyframes + animation - dla złożonych i ciągłych animacji:

  • Pulsowanie, obracanie, latanie
  • Animacje wieloetapowe (więcej niż 2 stany)
  • Nieskończone animacje tła lub dekoracji

React Transition Group - dla animacji cyklu życia komponentów:

  • Animowane montowanie/odmontowanie elementów
  • Listy z animowanym dodawaniem/usuwaniem elementów
  • Przejścia między widokami/stronami

Dobrze zaprojektowane animacje to jak system nawigacyjny statku - prowadzą użytkownika, dają feedback i sprawiają, że interfejs czuje się naturalnie, jak lot przez galaktykę z warp drive, a nie teleportacja bez ostrzeżenia.

Kod do tej lekcji: 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;
  }
`;

// ===== ANIMACJE KEYFRAMES =====

// 1. Rotacja - idealna dla spinnerów
const spin = keyframes`
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
`;

// 2. Pulsowanie - efekt bicia serca
const pulse = keyframes`
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.05); opacity: 0.8; }
`;

// 3. Efekt unoszenia się (float)
const float = keyframes`
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-12px); }
`;

// 4. Efekt świecenia (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. Wejście z lewej strony
const slideInLeft = keyframes`
  from {
    opacity: 0;
    transform: translateX(-60px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
`;

// TODO: Stwórz animację fadeInUp
// Element powinien pojawiać się od dołu z 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;
`;

// ===== PULSUJĄCY PRZYCISK =====
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;
  }
`;

// ===== ŚWIECĄCA KARTA =====
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;
  }
`;

// ===== ANIMOWANE KARTY Z OPÓŹNIENIEM =====
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: Stwórz komponent AnimatedBadge z animacją warunkową
// Gdy prop active=true -> animacja pulse
// Gdy active=false -> brak animacji
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: Stwórz OrbitDot - kropkę krążącą po okręgu
// Użyj @keyframes z transform: rotate() i 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;
`;

// ===== APLIKACJA =====
function App() {
  const [showCards, setShowCards] = useState(false);

  const missions = [
    { name: 'Missja Alpha', status: true },
    { name: 'Missja Beta', status: true },
    { name: 'Missja Gamma', status: false },
    { name: 'Missja Delta', status: true },
  ];

  return (
    <>
      <GlobalStyle />
      <Container>
        <Title>CSS Animations & Keyframes</Title>
        <Subtitle>Animacje w styled-components</Subtitle>

        {/* Sekcja: Spinner */}
        <Section delay="0s">
          <SectionTitle>Loading Spinner</SectionTitle>
          <SpinnerWrapper>
            <Spinner />
            <span>Skanowanie sektora kosmicznego...</span>
          </SpinnerWrapper>
        </Section>

        {/* Sekcja: Pulsujący przycisk */}
        <Section delay="0.15s">
          <SectionTitle>Pulsujący przycisk</SectionTitle>
          <PulseButton onClick={() => setShowCards(!showCards)}>
            {showCards ? 'Ukryj misje' : 'Pokaż misje'}
          </PulseButton>
        </Section>

        {/* Sekcja: Animowane karty z opóźnieniem */}
        {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>
        )}

        {/* Sekcja: Świecąca karta */}
        <Section delay="0.3s">
          <SectionTitle>Glow Effect</SectionTitle>
          <GlowCard>
            <h4>Stacja kosmiczna Nebula-7</h4>
            <p>Karta z efektem pulsującego świecenia CSS box-shadow.</p>
          </GlowCard>
        </Section>

        {/* Sekcja: Orbita */}
        <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>Orbita z użyciem rotate + translateX</span>
          </div>
        </Section>
      </Container>
    </>
  );
}

export default App;

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Zadania praktyczne w grze

  • Klikanie w kolejności

    Ułóż definicję CSS Custom Property:

  1. Kliknij w kolejnościPodstawy: CSS Custom Properties

Przydatne artykuły