Sub topic 1
What accessible components must do
Prerequisites
This chapter assumes you can write React function components with props and useState, and that you can read basic TypeScript. You don't need prior accessibility experience. You should know what a browser's Tab key does on a page. Later chapters on Radix UI and shadcn/ui rely on the vocabulary introduced here.
Why start with accessibility
An interactive component has two jobs. It has to look right, and it has to work for people who use a keyboard, a screen reader, voice control, or a switch device. The second job is the harder one to get right, and it is the reason headless libraries exist. The rest of this tutorial treats that behavior as a contract that Radix UI implements and shadcn/ui styles. To see why the contract is worth outsourcing, you need to know what it contains.
Every accessible component answers four questions for assistive technology:
- What is this? (role)
- What is it called? (accessible name)
- What state is it in? (states and properties)
- How do I operate it? (focus and keyboard interaction)
Roles, names, and states
The browser builds an accessibility tree alongside the DOM. Screen readers read that tree, not your pixels. Each node has a role, a name, and optional states.
- Role: the kind of control, such as
button,checkbox,dialog,tab, ormenuitem. - Accessible name: the label announced for the control. It comes from visible text, a
<label>,aria-label, oraria-labelledby. - State and properties: values like
aria-expanded,aria-pressed,aria-selected,aria-checked, andaria-invalid.
Native HTML elements supply all of this for free. A <button> has the role button, takes its name from its text, is focusable, and responds to Enter and Space. A <div onClick> has none of that.
export function BadMute({ onToggle }: { onToggle: () => void }) {
return (
<div className="btn" onClick={onToggle}>
Mute
</div>
)
}This component can't be reached with Tab. A screen reader announces it as plain text. Keyboard users can't activate it. Compare the native version, which also reports state:
import { useState } from "react"
export function MuteToggle() {
const [muted, setMuted] = useState(false)
return (
<button
type="button"
aria-pressed={muted}
onClick={() => setMuted(!muted)}
>
Mute
</button>
)
}A screen reader announces "Mute, toggle button, not pressed", then "pressed" after activation. Nothing was added except one attribute, because the element did the rest.
You need ARIA when no native element matches the pattern. Examples are tabs, comboboxes, menus, and dialogs with custom layouts. These are the components that headless libraries exist to build.
Focus
Focus is the single element that receives keyboard input. A component must manage it in four situations.
- Reachability. Interactive elements must be in the tab order. Native controls are. Custom ones need
tabIndex={0}. Avoid positivetabIndexvalues, which reorder the page unpredictably. - Visibility. The focused element needs a visible indicator. Removing
outlinewithout a replacement hides it. This is why the shadcn/ui button source you'll see later includesfocus-visible:ring-2. The:focus-visibleselector shows the ring for keyboard focus but usually not for mouse clicks. - Containment. While a modal dialog is open, Tab and Shift+Tab must cycle inside it. Otherwise focus escapes to the page behind the overlay, which a screen reader user can't see is inert.
- Restoration. When the dialog closes, focus must return to the element that opened it. If it doesn't, focus resets to the top of the document, and keyboard users lose their place.
A modal dialog therefore has this sequence:
Keyboard interaction
Users expect the same keys to do the same things across widgets. The WAI-ARIA Authoring Practices Guide documents the expected keys for each pattern. Some common ones:
| Widget | Keys | Expected behavior |
|---|---|---|
| Button | Enter, Space | Activate |
| Checkbox | Space | Toggle |
| Dialog | Escape, Tab | Close, cycle focus inside |
| Tabs | Left/Right arrows, Home, End | Move between tabs |
| Menu | Up/Down arrows, Enter, Escape | Move, choose, close |
| Select/listbox | Up/Down arrows, typing a letter | Move, jump to a match |
Composite widgets such as tabs, menus, and radio groups use a technique called roving tabindex. Only one item in the group has tabIndex={0}, and the rest have -1. Tab enters the group once and leaves it once. The arrow keys move focus within it. Without this, a toolbar with twenty buttons costs a keyboard user twenty Tab presses to cross.
Here is a complete tab list that does this by hand:
import { useRef, useState, type KeyboardEvent } from "react"
const tabs = ["Account", "Billing", "Team"]
export function SettingsTabs() {
const [active, setActive] = useState(0)
const refs = useRef<(HTMLButtonElement | null)[]>([])
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
let next = active
if (event.key === "ArrowRight") next = (active + 1) % tabs.length
else if (event.key === "ArrowLeft") next = (active - 1 + tabs.length) % tabs.length
else if (event.key === "Home") next = 0
else if (event.key === "End") next = tabs.length - 1
else return
event.preventDefault()
setActive(next)
refs.current[next]?.focus()
}
return (
<div>
<div role="tablist" aria-label="Settings" onKeyDown={onKeyDown}>
{tabs.map((tab, i) => (
<button
key={tab}
ref={(el) => {
refs.current[i] = el
}}
type="button"
role="tab"
id={`tab-${i}`}
aria-selected={active === i}
aria-controls={`panel-${i}`}
tabIndex={active === i ? 0 : -1}
onClick={() => setActive(i)}
>
{tab}
</button>
))}
</div>
{tabs.map((tab, i) => (
<div
key={tab}
role="tabpanel"
id={`panel-${i}`}
aria-labelledby={`tab-${i}`}
hidden={active !== i}
>
{tab} settings
</div>
))}
</div>
)
}Count what this 50-line component had to get right: three roles, five ARIA attributes, id linking between tabs and panels, a roving tabIndex, four navigation keys, wraparound, and programmatic focus. It still omits several things a production tab list needs, such as vertical orientation, right-to-left layouts, and disabled tabs. Repeating this for every widget in an application is slow and easy to get subtly wrong.
Common errors
- Clickable non-interactive elements. A
divorspanwithonClickand no role,tabIndex, or key handler. - Missing names. An icon-only button with no
aria-label. A screen reader announces just "button". - Stale state.
aria-expandedthat is hardcoded or not updated when the panel opens. - Hiding focus.
outline: nonewith no replacement style. - Unrestored focus. Closing a custom modal and leaving focus on a removed element.
- Wrong placement of handlers. Putting
onClickon a wrapper around a button instead of the button, which can double-fire or skip keyboard activation. - Contradicting the role. Adding
role="button"to a link that navigates, so the element behaves as one thing and is announced as another.
What this means for the rest of the tutorial
The contract above is the same for every project, and none of it depends on colors or spacing. Behavior and appearance can therefore be separated. A library can own the roles, focus, and keys. Your application owns the visual design. The next chapter defines that split as headless components.
Exercise
A teammate builds an icon-only close button as <span onClick={close}><XIcon /></span>. List the accessibility failures and give a corrected version.
Show answer
The span has no button role, so assistive technology doesn't announce it as a control. It isn't focusable, so keyboard users can't reach it. Enter and Space do nothing. It also has no accessible name, because the icon has no text. The fix is a native button with a name: <button type="button" aria-label="Close" onClick={close}><XIcon aria-hidden="true" /></button>. The native element gives focusability and key activation. The aria-label provides the name, and aria-hidden stops the icon from adding noise.
Exercise
In the SettingsTabs example, what would happen to keyboard users if every tab had tabIndex={0} instead of the roving values, and why does the arrow-key handler call event.preventDefault()?
Show answer
Every tab would be a separate Tab stop, so a keyboard user would press Tab once per tab to cross the group, and arrow keys would not be the expected way to move. The handler calls preventDefault() so that keys like Home and End don't also scroll the page while they move focus between tabs.