JavaScript and React course ยท Module 8: Advanced React Patterns

Accessibility (a11y) in React

6 min read ยท
In this lesson9

On a space station, every crew member must have access to the control systems - regardless of whether they operate them by sight, touch, or voice commands. Accessibility (a11y for short) in web applications works exactly the same way. When building a React interface, we must ensure that every user can use it - blind people using screen readers, people who navigate only by keyboard, or people with color vision deficiencies.

Why is accessibility important?

According to WHO, over a billion people worldwide live with some form of disability. This means that an inaccessible application excludes a huge group of potential users. Beyond the ethical aspect, accessibility:

  • Is legally required in many countries (WCAG, ADA)
  • Improves SEO and overall code quality
  • Makes the application easier to use for ALL users (e.g., on mobile devices)
  • Makes the interface more predictable and testable

Semantic HTML in React

The foundation of accessibility is using the right HTML elements. React encourages creating components, but it is easy to fall into the trap of overusing <div>:

// BAD - "div soup" - screen reader doesn't understand the structure
function BadNavigation() {
  return (
    <div className="nav">
      <div className="nav-item" onClick={goHome}>Home</div>
      <div className="nav-item" onClick={goMissions}>Missions</div>
      <div className="nav-item" onClick={goCrewPanel}>Crew</div>
    </div>
  );
}

// GOOD - semantic HTML elements
function GoodNavigation() {
  return (
    <nav aria-label="Station main menu">
      <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/missions">Missions</a></li>
        <li><a href="/crew">Crew</a></li>
      </ul>
    </nav>
  );
}

Key semantic elements include: <nav>, <main>, <header>, <footer>, <section>, <article>, <aside>, <button>, <form>, <label>.

ARIA attributes in React

ARIA (Accessible Rich Internet Applications) is a set of attributes that add information about the role and state of elements for assistive technologies. In React, we use them in camelCase or with hyphens:

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">Search galaxies:</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>
  );
}

Most commonly used ARIA attributes in React:

AttributeUse case
roleDefines the element's role (alert, dialog, tabpanel)
aria-labelText label for the element
aria-labelledbyID of the element that serves as the label
aria-describedbyID of the element with additional description
aria-liveAnnounces dynamic content changes
aria-expandedWhether the element is expanded
aria-hiddenHides the element from the screen reader
aria-disabledIndicates a disabled element

Focus management

In SPA (Single Page Application) applications, managing keyboard focus is critical. When a user navigates with the keyboard, focus must move in a logical order:

import { useRef, useEffect } from 'react';

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

  // Move focus to the modal after opening
  useEffect(() => {
    if (isOpen && closeButtonRef.current) {
      closeButtonRef.current.focus();
    }
  }, [isOpen]);

  // Focus trap - Tab doesn't leave the 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}>
          Close
        </button>
      </div>
    </div>
  );
}

Keyboard navigation

Every interactive element must be accessible from the keyboard. React supports key handling through onKeyDown, onKeyUp, and 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="Select a spaceship"
      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>
  );
}

Announcing dynamic changes (Live Regions)

When page content changes dynamically (e.g., a notification appears), the screen reader must be informed. We use aria-live:

function MissionStatusBoard() {
  const [status, setStatus] = useState('Awaiting launch');
  const [logs, setLogs] = useState([]);

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

  return (
    <div>
      {/* aria-live="polite" - waits for the reader to finish current text */}
      <div aria-live="polite" aria-atomic="true">
        <h2>Mission status: {status}</h2>
      </div>

      {/* aria-live="assertive" - interrupts current reading */}
      <div aria-live="assertive" className="sr-only">
        {logs.length > 0 && logs[logs.length - 1]}
      </div>

      <button onClick={() => updateStatus('Countdown started')}>
        Start countdown
      </button>
      <button onClick={() => updateStatus('Launch!')}>
        Launch
      </button>
    </div>
  );
}

The sr-only class (screen reader only)

Sometimes we need text that is visible only to screen readers:

// CSS style to visually hide, but not from screen readers
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>
  );
}

// Usage
<IconButton icon="โ–ฒ" label="Start mission" onClick={startMission} />

Accessible forms

Forms are one of the most important areas of accessibility. Every field must have a label, and errors must be clearly communicated:

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

  return (
    <form aria-label="Crew member registration">
      <div>
        <label htmlFor="crew-name">Full name:</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>Specialization:</legend>
        <label>
          <input type="radio" name="role" value="pilot" />
          Pilot
        </label>
        <label>
          <input type="radio" name="role" value="engineer" />
          Engineer
        </label>
        <label>
          <input type="radio" name="role" value="scientist" />
          Scientist
        </label>
      </fieldset>

      <button type="submit">Join the crew</button>
    </form>
  );
}

Summary

Accessibility in React is not an add-on, but an integral part of the interface creation process:

  • Semantic HTML is the foundation - use <nav>, <main>, <button> instead of <div> for everything
  • ARIA attributes supplement semantics when native elements are not enough
  • Focus management is critical in SPAs - a modal must "trap" focus, navigation must be logical
  • Keyboard navigation - every interactive element must be accessible without a mouse
  • Live regions (aria-live) announce dynamic content changes
  • Forms require labels, error descriptions, and appropriate roles

Just as space station systems must be designed so that every crew member can use them under all conditions - even when the lights go out and the touchscreen stops working - an accessible React application ensures that every user can effectively use it.

Code for this lesson: App.jsx
import React, { useState, useRef, useEffect } from 'react';

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

// --- Component 1: Navigation with ARIA ---
function SpaceNavigation() {
  return (
    <nav aria-label="Main menu of the space station">
      <ul style={navListStyle}>
        {[
          { label: 'Control Panel', icon: '' },
          { label: 'Star Map', icon: '' },
          { label: 'Crew', icon: '' },
          { label: 'Systems', 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>
  );
}

// --- Component 2: Modal with 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}>
          Close (Esc)
        </button>
      </div>
    </div>
  );
}

// --- Component 3: List with keyboard navigation ---
function ShipSelector() {
  const ships = [
    { id: 1, name: 'Aurora', type: 'Cruiser', crew: 120 },
    { id: 2, name: 'Nebula', type: 'Frigate', crew: 45 },
    { id: 3, name: 'Vortex', type: 'Fighter', crew: 2 },
    { id: 4, name: 'Horizon', type: 'Transporter', crew: 300 },
    { id: 5, name: 'Eclipse', type: 'Scout', 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}>Select a ship (navigate with arrow keys)</h3>
      <ul
        role="listbox"
        aria-label="List of spaceships"
        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 }}>Crew: {ship.crew}</span>
          </li>
        ))}
      </ul>
      {selected && (
        <div aria-live="polite" style={selectedStyle}>
          Selected ship: <strong>{selected.name}</strong> ({selected.type})
        </div>
      )}
    </div>
  );
}

// --- Component 4: Form with validation ---
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 = 'Name is required';
    if (!role) newErrors.role = 'Choose a specialization';
    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="Crew member registration">
      <h3 style={headingStyle}>Crew Registration</h3>

      <div style={{ marginBottom: '12px' }}>
        <label htmlFor="crew-name" style={labelStyle}>Full name:</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' }}>Specialization:</legend>
        {['pilot', 'engineer', 'scientist', 'medic'].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}>
        Join the Crew
      </button>

      {submitted && (
        <div aria-live="assertive" role="alert" style={successStyle}>
          Registration completed successfully!
        </div>
      )}
    </form>
  );
}

// --- Component 5: Live region ---
function MissionStatus() {
  const [status, setStatus] = useState('Waiting');
  const statuses = ['Waiting', 'Countdown', 'Launch!', 'In flight', 'Orbit achieved'];

  return (
    <div>
      <h3 style={headingStyle}>Mission status (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) in React
      </h1>
      <p style={{ textAlign: 'center', opacity: 0.6, marginBottom: '24px', fontSize: '13px' }}>
        Test Tab, arrow keys, Enter, Esc
      </p>

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

      <section style={sectionStyle}>
        <h2 style={{ color: '#00d4ff', marginBottom: '10px' }}>Modal with focus trap</h2>
        <button onClick={() => setModalOpen(true)} style={navBtnStyle}>
          Open mission modal
        </button>
        <AccessibleModal
          isOpen={modalOpen}
          onClose={() => setModalOpen(false)}
          title="Alpha Mission Details"
        >
          <p>Goal: Exploration of the Kepler-442 system.</p>
          <p>Duration: 18 months.</p>
          <input placeholder="Add a note..." 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;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the main purpose of the Adapter pattern in React?

  2. 2. How do we most commonly implement the Facade pattern in React?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Arrange the accessibility attributes for an input field with a validation error:

  • Code editor

    Virtualized list with optimizations

  • Click in order

    Arrange the React.forwardRef syntax:

  • Vertical ordering

    Arrange the HOC implementation:

  • Code editor

    Advanced Error Boundary

  1. QuestionAdapter Pattern
  2. QuestionFacade Pattern
  3. QuestionAdapter vs Facade
  4. Click in orderARIA Attributes in a Form
  5. QuestionFocus Management in a Modal
  6. Coding taskPractice: Virtualized List with Memoization
  7. Click in orderforwardRef in React
  8. Put in orderIntroduction: HOC Implementation Pattern
  9. Coding taskPractice: Error Boundary

Useful articles