21. Accessibility (a11y) in React
Why Accessibility Matters
Accessibility (shortened as a11y) makes your app usable by everyone—including people with visual, motor, or cognitive impairments. It also improves overall usability and even boosts SEO. In many countries, accessible apps are a legal requirement for public-facing businesses.
Use Semantic HTML First
React doesn’t fix accessibility by default—it still depends on how you write HTML. Always use semantic elements instead of generic <div> tags.
// ❌ Bad
div onClick={() => setOpen(true)}>Open</div>
// ✅ Better
<button onClick={() => setOpen(true)}>Open</button>Add Accessible Labels
Screen readers rely on labels to describe elements. Use aria-label or htmlFor when needed.
<label htmlFor="email">Email Address</label>
<input id="email" type="email" /><button aria-label="Close modal">✖</button>Keyboard Navigation Support
Everything interactive must be usable with the keyboard only—no mouse. Test with the Tab key!
<button onKeyDown={(e) => e.key === 'Enter' && handleClick()}>
Submit
</button>Use ARIA Only When Needed
ARIA improves accessibility but should not replace semantic HTML. Use it for dynamic UI components like modals, dropdowns, and tabs.
<div role="alert">
Form submission failed. Try again.
</div>Accessibility Checklist
- All buttons use <button> or role="button"
- Images include alt text
- Forms have labels
- Keyboard navigation works
- Focusable elements are visible
- Color contrast passes WCAG AA
Common ARIA Attributes
| Attribute | Purpose | Example |
|---|---|---|
| aria-label | Provides label text for screen readers | <button aria-label='Close' /> |
| aria-hidden | Hides content from screen readers | <span aria-hidden='true'>★</span> |
| role | Defines custom component role | <div role='alert' /> |
| aria-live | Announces dynamic content | <div aria-live='polite' /> |
Helpful Testing Tools
- axe DevTools (browser extension)
- Lighthouse (Chrome DevTools)
- NVDA or VoiceOver (screen readers)
- Keyboard Tab test
Mini Project Step
Go back to your project and make sure your UI is keyboard accessible. Replace any clickable <div> with real buttons and add aria-labels for icons.