ARIA and keyboard
- React course
- Advanced
- Lesson 42/56
- 4 min
Learn aria-label, aria-expanded and keyboard usage.
Accordion and ARIA
In an accordion each header must be a <button> carrying aria-expanded and aria-controls. The panel gets role="region" and aria-labelledby pointing back to the header.
Keyboard users move between headers with Tab; Enter toggles the panel. Home and End jump to the first and last header.
Never remove the focus ring; only slim it down with :focus-visible.
Focus management
When a modal opens, focus must move inside it; on close it returns to the trigger. This is called a focus trap.
In React you keep a useRef to the modal root and call ref.current.focus() inside a useEffect. On close you restore the previous focus.
The modal root carries role="dialog" and aria-modal="true".
Practice Write the AccessibleModal skeleton
Write an AccessibleModal component. Keep a ref with useRef(null) and call ref.current.focus() in a useEffect. The root should be <div role="dialog" aria-modal="true" tabIndex="-1" ref={ref}>. Export it.
Starter code
import { useRef, useEffect } from 'react';
// Write the AccessibleModal component hereSample solution
import { useRef, useEffect } from 'react';
function AccessibleModal() {
const ref = useRef(null);
useEffect(() => {
ref.current.focus();
}, []);
return (
<div role="dialog" aria-modal="true" tabIndex="-1" ref={ref}>
Content
</div>
);
}
export default AccessibleModal;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: link the panel to the header
<button aria-expanded={open} aria-controls="panel-1">Header</button>
<div id="panel-1" role="____" aria-labelledby="btn-1">Content</div>
<button aria-expanded={open} aria-controls="panel-1">Header</button>
<div id="panel-1" role="region" aria-labelledby="btn-1">Content</div>
Explanation: answer: region. A toggle panel uses role region.
2 When a modal opens, what should focus do?
- Go to the top of the page
- Move into the modal and return to the trigger on close Correct answer
- Stay unchanged
- Move only for screen readers
Explanation: In on open, back to the trigger on close.
3 Match keyboard and ARIA
| Term | Meaning |
|---|---|
Tab |
Moves between focusable items |
Enter |
Triggers button |
Esc |
Closes modal |
Shift+Tab |
Goes backwards |