Kurs JavaScript i React · Moduł 8: Zaawansowane wzorce React

Accessibility (a11y) w React

6 min czytania ·
W tej lekcji9

Na stacji kosmicznej każdy członek załogi musi mieć dostęp do systemów sterowania - niezależnie od tego, czy obsługuje je wzrokiem, dotykiem czy komendami głosowymi. Dokładnie tak samo działa dostępność (accessibility, w skrócie a11y) w aplikacjach webowych. Budując interfejs w React, musimy zadbać o to, by każdy użytkownik mógł z niego korzystać - osoby niewidome używające czytników ekranu, osoby poruszające się tylko klawiaturą, czy osoby z zaburzeniami widzenia kolorów.

Dlaczego dostępność jest ważna?

Według WHO, ponad miliard ludzi na świecie żyje z jakąś formą niepełnosprawności. To oznacza, że aplikacja niedostępna wyklucza ogromną grupę potencjalnych użytkowników. Poza aspektem etycznym, dostępność:

  • Jest wymagana prawnie w wielu krajach (WCAG, ADA)
  • Poprawia SEO i ogólną jakość kodu
  • Ułatwia korzystanie z aplikacji WSZYSTKIM użytkownikom (np. na urządzeniach mobilnych)
  • Sprawia, że interfejs jest bardziej przewidywalny i testowalny

Semantyczny HTML w React

Fundamentem dostępności jest używanie właściwych elementów HTML. React zachęca do tworzenia komponentów, ale łatwo wpaść w pułapkę nadużywania <div>:

// ŹLE - "div soup" - czytnik ekranu nie rozumie struktury
function BadNavigation() {
  return (
    <div className="nav">
      <div className="nav-item" onClick={goHome}>Start</div>
      <div className="nav-item" onClick={goMissions}>Misje</div>
      <div className="nav-item" onClick={goCrewPanel}>Załoga</div>
    </div>
  );
}

// DOBRZE - semantyczne elementy HTML
function GoodNavigation() {
  return (
    <nav aria-label="Menu główne stacji">
      <ul>
        <li><a href="/">Start</a></li>
        <li><a href="/missions">Misje</a></li>
        <li><a href="/crew">Załoga</a></li>
      </ul>
    </nav>
  );
}

Kluczowe semantyczne elementy to: <nav>, <main>, <header>, <footer>, <section>, <article>, <aside>, <button>, <form>, <label>.

Atrybuty ARIA w React

ARIA (Accessible Rich Internet Applications) to zbiór atrybutów, które dodają informacje o roli i stanie elementów dla technologii asystujących. W React używamy ich w formacie camelCase lub z myślnikami:

function MissionAlert({ message, severity }) {
  return (
    <div
      role="alert"
      aria-live="assertive"
      aria-atomic="true"
      className={severity}
    >
      {message}
    </div>
  );
}

function SearchField() {
  const [results, setResults] = useState([]);
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <label htmlFor="galaxy-search">Szukaj galaktyk:</label>
      <input
        id="galaxy-search"
        type="search"
        role="combobox"
        aria-expanded={isOpen}
        aria-controls="search-results"
        aria-autocomplete="list"
        aria-haspopup="listbox"
      />
      {isOpen && (
        <ul id="search-results" role="listbox">
          {results.map(r => (
            <li key={r.id} role="option">{r.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

Najczęściej używane atrybuty ARIA w React:

AtrybutZastosowanie
roleDefiniuje rolę elementu (alert, dialog, tabpanel)
aria-labelTekstowa etykieta dla elementu
aria-labelledbyID elementu, który jest etykietą
aria-describedbyID elementu z dodatkowym opisem
aria-liveOgłasza dynamiczne zmiany treści
aria-expandedCzy element jest rozwinięty
aria-hiddenUkrywa element przed czytnikiem
aria-disabledWskazuje element nieaktywny

Zarządzanie fokusem

W aplikacjach SPA (Single Page Application) zarządzanie fokusem klawiatury jest krytyczne. Gdy użytkownik nawiguje klawiaturą, fokus musi przesuwać się w logicznej kolejności:

import { useRef, useEffect } from 'react';

function MissionModal({ isOpen, onClose, title, children }) {
  const modalRef = useRef(null);
  const closeButtonRef = useRef(null);

  // Przenieś fokus do modala po otwarciu
  useEffect(() => {
    if (isOpen && closeButtonRef.current) {
      closeButtonRef.current.focus();
    }
  }, [isOpen]);

  // Pułapka fokusa - Tab nie wychodzi poza modal
  const handleKeyDown = (e) => {
    if (e.key === 'Escape') {
      onClose();
    }

    if (e.key === 'Tab') {
      const focusableElements = modalRef.current.querySelectorAll(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      );
      const firstElement = focusableElements[0];
      const lastElement = focusableElements[focusableElements.length - 1];

      if (e.shiftKey && document.activeElement === firstElement) {
        e.preventDefault();
        lastElement.focus();
      } else if (!e.shiftKey && document.activeElement === lastElement) {
        e.preventDefault();
        firstElement.focus();
      }
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="modal-overlay"
      role="dialog"
      aria-modal="true"
      aria-labelledby="modal-title"
      ref={modalRef}
      onKeyDown={handleKeyDown}
    >
      <div className="modal-content">
        <h2 id="modal-title">{title}</h2>
        {children}
        <button ref={closeButtonRef} onClick={onClose}>
          Zamknij
        </button>
      </div>
    </div>
  );
}

Nawigacja klawiaturą

Każdy interaktywny element musi być dostępny z klawiatury. React wspiera obsługę klawiszy przez onKeyDown, onKeyUp i onKeyPress:

function SpaceshipSelector({ ships, onSelect }) {
  const [activeIndex, setActiveIndex] = useState(0);

  const handleKeyDown = (e) => {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setActiveIndex(prev => Math.min(prev + 1, ships.length - 1));
        break;
      case 'ArrowUp':
        e.preventDefault();
        setActiveIndex(prev => Math.max(prev - 1, 0));
        break;
      case 'Enter':
      case ' ':
        e.preventDefault();
        onSelect(ships[activeIndex]);
        break;
    }
  };

  return (
    <ul
      role="listbox"
      aria-label="Wybierz statek kosmiczny"
      tabIndex={0}
      onKeyDown={handleKeyDown}
    >
      {ships.map((ship, index) => (
        <li
          key={ship.id}
          role="option"
          aria-selected={index === activeIndex}
          onClick={() => onSelect(ship)}
          style={{
            background: index === activeIndex ? '#1a3a5c' : 'transparent',
          }}
        >
          {ship.name} - {ship.type}
        </li>
      ))}
    </ul>
  );
}

Ogłaszanie zmian dynamicznych (Live Regions)

Gdy treść strony zmienia się dynamicznie (np. pojawia się powiadomienie), czytnik ekranu musi o tym wiedzieć. Używamy aria-live:

function MissionStatusBoard() {
  const [status, setStatus] = useState('Oczekiwanie na start');
  const [logs, setLogs] = useState([]);

  const updateStatus = (newStatus) => {
    setStatus(newStatus);
    setLogs(prev => [...prev, newStatus]);
  };

  return (
    <div>
      {/* aria-live="polite" - czeka aż czytnik skończy bieżący tekst */}
      <div aria-live="polite" aria-atomic="true">
        <h2>Status misji: {status}</h2>
      </div>

      {/* aria-live="assertive" - przerywa bieżące czytanie */}
      <div aria-live="assertive" className="sr-only">
        {logs.length > 0 && logs[logs.length - 1]}
      </div>

      <button onClick={() => updateStatus('Odliczanie rozpoczęte')}>
        Rozpocznij odliczanie
      </button>
      <button onClick={() => updateStatus('Start!')}>
        Start
      </button>
    </div>
  );
}

Klasa sr-only (screen reader only)

Czasami potrzebujemy tekstu widocznego tylko dla czytników ekranu:

// Styl CSS do ukrycia wizualnego, ale nie dla czytników ekranu
const srOnlyStyle = {
  position: 'absolute',
  width: '1px',
  height: '1px',
  padding: 0,
  margin: '-1px',
  overflow: 'hidden',
  clip: 'rect(0, 0, 0, 0)',
  whiteSpace: 'nowrap',
  borderWidth: 0,
};

function IconButton({ icon, label, onClick }) {
  return (
    <button onClick={onClick} aria-label={label}>
      <span aria-hidden="true">{icon}</span>
      <span style={srOnlyStyle}>{label}</span>
    </button>
  );
}

// Użycie
<IconButton icon="▲" label="Rozpocznij misję" onClick={startMission} />

Formularze dostępne

Formularze to jeden z najważniejszych obszarów dostępności. Każde pole musi mieć etykietę, a błędy muszą być jasno komunikowane:

function CrewRegistrationForm() {
  const [errors, setErrors] = useState({});

  return (
    <form aria-label="Rejestracja członka załogi">
      <div>
        <label htmlFor="crew-name">Imię i nazwisko:</label>
        <input
          id="crew-name"
          type="text"
          aria-required="true"
          aria-invalid={!!errors.name}
          aria-describedby={errors.name ? 'name-error' : undefined}
        />
        {errors.name && (
          <span id="name-error" role="alert" style={{ color: 'red' }}>
            {errors.name}
          </span>
        )}
      </div>

      <fieldset>
        <legend>Specjalizacja:</legend>
        <label>
          <input type="radio" name="role" value="pilot" />
          Pilot
        </label>
        <label>
          <input type="radio" name="role" value="engineer" />
          Inżynier
        </label>
        <label>
          <input type="radio" name="role" value="scientist" />
          Naukowiec
        </label>
      </fieldset>

      <button type="submit">Dołącz do załogi</button>
    </form>
  );
}

Podsumowanie

Dostępność w React to nie dodatek, ale integralna część procesu tworzenia interfejsu:

  • Semantyczny HTML to fundament - używaj <nav>, <main>, <button> zamiast <div> na wszystko
  • Atrybuty ARIA uzupełniają semantykę, gdy natywne elementy nie wystarczają
  • Zarządzanie fokusem jest krytyczne w SPA - modal musi "pułapkować" fokus, nawigacja musi być logiczna
  • Nawigacja klawiaturą - każdy interaktywny element musi być dostępny bez myszy
  • Live regions (aria-live) ogłaszają dynamiczne zmiany treści
  • Formularze wymagają etykiet, opisów błędów i odpowiednich ról

Podobnie jak systemy stacji kosmicznej muszą być zaprojektowane tak, by każdy członek załogi mógł z nich korzystać w każdych warunkach - nawet gdy światła zgasną, a ekran dotykowy przestanie działać - tak dostępna aplikacja React zapewnia, że każdy użytkownik może skutecznie z niej korzystać.

Kod do tej lekcji: App.jsx
import React, { useState, useRef, useEffect } from 'react';

// ============================================
// DEMO: Accessibility (a11y) w React
// ============================================

// --- Komponent 1: Nawigacja z ARIA ---
function SpaceNavigation() {
  return (
    <nav aria-label="Menu glowne stacji kosmicznej">
      <ul style={navListStyle}>
        {[
          { label: 'Panel kontroli', icon: '' },
          { label: 'Mapa gwiazd', icon: '' },
          { label: 'Zaloga', icon: '' },
          { label: 'Systemy', icon: '' },
        ].map(item => (
          <li key={item.label}>
            <button
              style={navBtnStyle}
              aria-label={item.label}
              onClick={() => alert(item.label)}
            >
              <span aria-hidden="true">{item.icon}</span>
              <span>{item.label}</span>
            </button>
          </li>
        ))}
      </ul>
    </nav>
  );
}

// --- Komponent 2: Modal z focus trap ---
function AccessibleModal({ isOpen, onClose, title, children }) {
  const modalRef = useRef(null);
  const closeRef = useRef(null);

  useEffect(() => {
    if (isOpen && closeRef.current) {
      closeRef.current.focus();
    }
  }, [isOpen]);

  const handleKeyDown = (e) => {
    if (e.key === 'Escape') onClose();

    if (e.key === 'Tab' && modalRef.current) {
      const focusable = modalRef.current.querySelectorAll(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      );
      const first = focusable[0];
      const last = focusable[focusable.length - 1];

      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    }
  };

  if (!isOpen) return null;

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div
        ref={modalRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="modal-title"
        style={modalStyle}
        onClick={(e) => e.stopPropagation()}
        onKeyDown={handleKeyDown}
      >
        <h2 id="modal-title" style={{ color: '#00d4ff', marginBottom: '12px' }}>
          {title}
        </h2>
        {children}
        <button ref={closeRef} onClick={onClose} style={closeBtnStyle}>
          Zamknij (Esc)
        </button>
      </div>
    </div>
  );
}

// --- Komponent 3: Lista z nawigacja klawiaturowa ---
function ShipSelector() {
  const ships = [
    { id: 1, name: 'Aurora', type: 'Krążownik', crew: 120 },
    { id: 2, name: 'Nebula', type: 'Fregata', crew: 45 },
    { id: 3, name: 'Vortex', type: 'Myśliwiec', crew: 2 },
    { id: 4, name: 'Horizon', type: 'Transporter', crew: 300 },
    { id: 5, name: 'Eclipse', type: 'Zwiadowca', crew: 8 },
  ];

  const [activeIndex, setActiveIndex] = useState(0);
  const [selected, setSelected] = useState(null);

  const handleKeyDown = (e) => {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setActiveIndex(prev => Math.min(prev + 1, ships.length - 1));
        break;
      case 'ArrowUp':
        e.preventDefault();
        setActiveIndex(prev => Math.max(prev - 1, 0));
        break;
      case 'Enter':
      case ' ':
        e.preventDefault();
        setSelected(ships[activeIndex]);
        break;
    }
  };

  return (
    <div>
      <h3 style={headingStyle}>Wybierz statek (nawiguj strzalkami)</h3>
      <ul
        role="listbox"
        aria-label="Lista statkow kosmicznych"
        tabIndex={0}
        onKeyDown={handleKeyDown}
        style={{ listStyle: 'none', padding: 0, outline: 'none' }}
      >
        {ships.map((ship, index) => (
          <li
            key={ship.id}
            role="option"
            aria-selected={index === activeIndex}
            onClick={() => { setActiveIndex(index); setSelected(ship); }}
            style={{
              padding: '10px 14px',
              background: index === activeIndex ? '#1a3a5c' : '#0d1b2a',
              borderRadius: '6px',
              marginBottom: '4px',
              cursor: 'pointer',
              border: index === activeIndex ? '1px solid #00d4ff' : '1px solid transparent',
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <span>{ship.name} - {ship.type}</span>
            <span style={{ opacity: 0.5 }}>Zaloga: {ship.crew}</span>
          </li>
        ))}
      </ul>
      {selected && (
        <div aria-live="polite" style={selectedStyle}>
          Wybrany statek: <strong>{selected.name}</strong> ({selected.type})
        </div>
      )}
    </div>
  );
}

// --- Komponent 4: Formularz z walidacja ---
function CrewForm() {
  const [name, setName] = useState('');
  const [role, setRole] = useState('');
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const validate = () => {
    const newErrors = {};
    if (!name.trim()) newErrors.name = 'Imie jest wymagane';
    if (!role) newErrors.role = 'Wybierz specjalizacje';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (validate()) {
      setSubmitted(true);
      setName('');
      setRole('');
      setTimeout(() => setSubmitted(false), 3000);
    }
  };

  return (
    <form onSubmit={handleSubmit} aria-label="Rejestracja czlonka zalogi">
      <h3 style={headingStyle}>Rejestracja zalogi</h3>

      <div style={{ marginBottom: '12px' }}>
        <label htmlFor="crew-name" style={labelStyle}>Imie i nazwisko:</label>
        <input
          id="crew-name"
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          aria-required="true"
          aria-invalid={!!errors.name}
          aria-describedby={errors.name ? 'name-error' : undefined}
          style={inputStyle}
        />
        {errors.name && (
          <span id="name-error" role="alert" style={errorStyle}>
            {errors.name}
          </span>
        )}
      </div>

      <fieldset style={{ border: '1px solid #1a3a5c', borderRadius: '6px', padding: '12px', marginBottom: '12px' }}>
        <legend style={{ color: '#00d4ff', padding: '0 8px' }}>Specjalizacja:</legend>
        {['pilot', 'inzynier', 'naukowiec', 'medyk'].map(r => (
          <label key={r} style={{ display: 'block', marginBottom: '6px', cursor: 'pointer' }}>
            <input
              type="radio"
              name="role"
              value={r}
              checked={role === r}
              onChange={(e) => setRole(e.target.value)}
              style={{ marginRight: '8px' }}
            />
            {r.charAt(0).toUpperCase() + r.slice(1)}
          </label>
        ))}
        {errors.role && (
          <span role="alert" style={errorStyle}>{errors.role}</span>
        )}
      </fieldset>

      <button type="submit" style={submitBtnStyle}>
        Dolacz do zalogi
      </button>

      {submitted && (
        <div aria-live="assertive" role="alert" style={successStyle}>
          Rejestracja zakonczona pomyslnie!
        </div>
      )}
    </form>
  );
}

// --- Komponent 5: Live region ---
function MissionStatus() {
  const [status, setStatus] = useState('Oczekiwanie');
  const statuses = ['Oczekiwanie', 'Odliczanie', 'Start!', 'W locie', 'Orbita osiagnieta'];

  return (
    <div>
      <h3 style={headingStyle}>Status misji (aria-live)</h3>
      <div aria-live="polite" aria-atomic="true" style={statusBoxStyle}>
        Status: <strong style={{ color: '#ffd700' }}>{status}</strong>
      </div>
      <div style={{ display: 'flex', gap: '6px', marginTop: '8px', flexWrap: 'wrap' }}>
        {statuses.map(s => (
          <button
            key={s}
            onClick={() => setStatus(s)}
            style={{
              ...navBtnStyle,
              background: status === s ? '#00d4ff' : '#1a2a3a',
              color: status === s ? '#000' : '#fff',
            }}
          >
            {s}
          </button>
        ))}
      </div>
    </div>
  );
}

// --- Style ---
const navListStyle = { listStyle: 'none', padding: 0, display: 'flex', gap: '6px', flexWrap: 'wrap' };
const navBtnStyle = {
  padding: '8px 14px', background: '#1a2a3a', border: 'none',
  borderRadius: '6px', color: '#fff', cursor: 'pointer', fontSize: '13px',
  display: 'flex', gap: '6px', alignItems: 'center',
};
const overlayStyle = {
  position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
  background: 'rgba(0,0,0,0.7)', display: 'flex',
  alignItems: 'center', justifyContent: 'center', zIndex: 1000,
};
const modalStyle = {
  background: '#0d1b2a', borderRadius: '12px', padding: '24px',
  maxWidth: '400px', width: '90%', border: '1px solid #1a3a5c',
};
const closeBtnStyle = {
  marginTop: '16px', padding: '8px 16px', background: '#f44336',
  border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer',
};
const headingStyle = { color: '#00d4ff', marginBottom: '10px', fontSize: '15px' };
const inputStyle = {
  width: '100%', padding: '8px', background: '#0d1b2a',
  border: '1px solid #1a3a5c', borderRadius: '6px', color: '#fff',
  fontSize: '14px', boxSizing: 'border-box',
};
const labelStyle = { display: 'block', marginBottom: '4px', color: '#00d4ff', fontSize: '13px' };
const errorStyle = { color: '#f44336', fontSize: '12px', display: 'block', marginTop: '4px' };
const submitBtnStyle = {
  padding: '10px 20px', background: '#4CAF50', border: 'none',
  borderRadius: '6px', color: '#fff', cursor: 'pointer', fontSize: '14px',
};
const successStyle = {
  marginTop: '12px', padding: '10px', background: '#1a3a1a',
  borderRadius: '6px', color: '#4CAF50', border: '1px solid #4CAF50',
};
const selectedStyle = {
  marginTop: '8px', padding: '10px', background: '#1a2a3a',
  borderRadius: '6px', border: '1px solid #00d4ff',
};
const statusBoxStyle = {
  padding: '12px', background: '#0d1b2a', borderRadius: '6px',
  border: '1px solid #1a3a5c',
};
const sectionStyle = {
  marginBottom: '24px', padding: '16px',
  background: 'rgba(255,255,255,0.03)', borderRadius: '12px',
  border: '1px solid rgba(255,255,255,0.08)',
};

function App() {
  const [modalOpen, setModalOpen] = useState(false);

  return (
    <div style={{ padding: '20px', background: '#0a0e1a', color: '#e0e0e0', minHeight: '100vh', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#ffd700', textAlign: 'center', marginBottom: '6px' }}>
        Accessibility (a11y) w React
      </h1>
      <p style={{ textAlign: 'center', opacity: 0.6, marginBottom: '24px', fontSize: '13px' }}>
        Testuj Tab, strzalki, Enter, Esc
      </p>

      <section style={sectionStyle}>
        <h2 style={{ color: '#00d4ff', marginBottom: '10px' }}>Semantyczna nawigacja</h2>
        <SpaceNavigation />
      </section>

      <section style={sectionStyle}>
        <h2 style={{ color: '#00d4ff', marginBottom: '10px' }}>Modal z focus trap</h2>
        <button onClick={() => setModalOpen(true)} style={navBtnStyle}>
          Otworz modal misji
        </button>
        <AccessibleModal
          isOpen={modalOpen}
          onClose={() => setModalOpen(false)}
          title="Szczegoly misji Alpha"
        >
          <p>Cel: Eksploracja systemu Kepler-442.</p>
          <p>Czas trwania: 18 miesiecy.</p>
          <input placeholder="Dodaj notatke..." style={{ ...inputStyle, marginTop: '8px' }} />
        </AccessibleModal>
      </section>

      <section style={sectionStyle}>
        <ShipSelector />
      </section>

      <section style={sectionStyle}>
        <MissionStatus />
      </section>

      <section style={sectionStyle}>
        <CrewForm />
      </section>
    </div>
  );
}

export default App;

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Jaki jest główny cel wzorca Adapter w React?

  2. 2. Jak najczęściej implementujemy wzorzec Facade w React?

To 2 z 4 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Klikanie w kolejności

    Ułóż atrybuty dostępności dla pola input z błędem walidacji:

  • Edytor kodu

    Wirtualizowana lista z optymalizacjami

  • Klikanie w kolejności

    Ułóż składnię React.forwardRef:

  • Układanie w pionie

    Uporządkuj implementację HOC:

  • Edytor kodu

    Zaawansowany Error Boundary

  1. PytanieWzorzec Adapter
  2. PytanieWzorzec Facade
  3. PytanieAdapter vs Facade
  4. Kliknij w kolejnościAtrybuty ARIA w formularzu
  5. PytanieZarządzanie fokusem w modalu
  6. Zadanie z kodemPraktyka: Wirtualizowana lista z memoizacją
  7. Kliknij w kolejnościforwardRef w React
  8. Ułóż w kolejnościWprowadzenie: Wzorzec implementacji HOC
  9. Zadanie z kodemPraktyka: Error boundary

Przydatne artykuły