Ensure accessibility by using semantic HTML elements, proper ARIA attributes (aria-label, role), managing focus for dynamic content, supporting keyboard navigation, using htmlFor with labels, and testing with tools like eslint-plugin-jsx-a11y and screen readers.
Core Principles:
Semantic HTML First:
<button>, <nav>, <main>, <header> instead of divsARIA Attributes:
Form Accessibility:
htmlFor (not for) to associate labels with inputsFocus Management:
Keyboard Navigation:
Testing Tools:
// BAD: Div soup
function BadNav() {
return (
<div className="nav">
<div onClick={goHome}>Home</div>
<div onClick={goAbout}>About</div>
</div>
);
}
// GOOD: Semantic HTML
function GoodNav() {
return (
<nav aria-label="Main navigation">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
);
}
// Accessible form with error messages
function AccessibleForm() {
const [error, setError] = useState('');
return (
<form>
<label htmlFor="email">Email Address</label>
<input
id="email"
type="email"
aria-describedby={error ? 'email-error' : 'email-hint'}
aria-invalid={!!error}
/>
<span id="email-hint" className="hint">
We'll never share your email
</span>
{error && (
<span id="email-error" className="error" role="alert">
{error}
</span>
)}
<button type="submit">Subscribe</button>
</form>
);
}