Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.
React forms are easier to use when controls have visible labels and keyboard behavior. In the typed search example, a hint and validation error stay associated with the field, while successful submission appears in its own status region. The review steps cover focus and announcements without logging private input.
Accessible React UI: Semantics, Labels, and Keyboard Use
Introduction
Start with elements that explain what they do: use <button> for actions, <a> for navigation, and form controls for input. A clickable <div> has no built-in keyboard behavior or control semantics.
The native element gives you useful behavior for free. The example below keeps a field’s label, hint, error, and submission feedback connected, then checks the form by keyboard.
Use native controls and labels
Before: placeholder as the only label
<form>
<input type="search" placeholder="Search articles" />
<button type="submit">Search</button>
</form>
The placeholder disappears as someone types, and it does not provide a persistent visible label. There is also no connected hint, validation error, or submission feedback. WAI recommends associating a label with each form control, usually with a <label> element (WAI form labels tutorial).
After: label, hint, error, and submission status
This version keeps field validation separate from the submission status:
import { useRef, useState, type FormEvent } from "react";
interface SearchFormProps {
onSearch: (query: string) => void;
}
export function SearchForm({ onSearch }: SearchFormProps) {
const [query, setQuery] = useState("");
const [fieldError, setFieldError] = useState<string | null>(null);
const [submitStatus, setSubmitStatus] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSubmitStatus("");
const value = query.trim();
if (!value) {
setFieldError("Enter a search term.");
inputRef.current?.focus();
return;
}
setFieldError(null);
onSearch(value);
setSubmitStatus("Search submitted.");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="site-search">Search articles</label>
<input
id="site-search"
ref={inputRef}
type="search"
value={query}
onChange={(event) => {
setQuery(event.currentTarget.value);
if (fieldError) setFieldError(null);
}}
aria-invalid={fieldError ? "true" : undefined}
aria-describedby={
fieldError ? "search-hint search-error" : "search-hint"
}
/>
<p id="search-hint">Enter a title or topic.</p>
{fieldError && <p id="search-error">{fieldError}</p>}
<button type="submit">Search</button>
<p role="status">{submitStatus}</p>
</form>
);
}
The <label> names the input, and aria-describedby points to the hint plus the error when one exists. An empty submission sets aria-invalid, shows the error, and focuses the field. Typing clears that error. A valid submission puts its confirmation in a separate role="status" region. WAI recommends connecting errors to their fields and giving feedback for successful submissions (WAI user notifications tutorial); the exact screen-reader announcement can vary by browser and assistive technology.
Keyboard and focus
People use Tab and Shift+Tab to move through a page, Enter or Space to activate buttons, and arrow keys in some controls. Keep the visible focus indicator; do not remove outlines without an equally clear replacement.
On validation failure, connect each message with aria-describedby and set aria-invalid="true". After submission, move focus to an error summary or the first invalid field. Reserve live regions for updates such as save messages or result counts that appear without a page change.
Verify this form
- Use Tab and Shift+Tab to reach the search field and button; check that focus is visible and the order makes sense. A screen reader should expose the field’s label and hint.
- Submit the empty form. Confirm focus returns to the field and the error is available with its description. Type a query and confirm the error clears.
- Submit a query. Confirm the status message is announced without moving focus. Check the keyboard path against WCAG keyboard guidance; status regions are defined by the WAI-ARIA status role.
flowchart LR
A[Keyboard or pointer action] --> B[Semantic control]
B --> C[React event handler]
C --> D[State or validation update]
D --> E[Focus and status feedback]
When to use ARIA
Use native buttons, links, labels, and form controls for the behavior they already provide. Add ARIA only when native HTML cannot express a needed name, relationship, or announcement; do not add ARIA roles to restate correct native semantics.
Trade-offs
| Need | Prefer | Trade-off |
|---|---|---|
| Trigger an action | <button> |
Built-in keyboard behavior; style its focus state clearly |
| Navigate to a URL | <a href> |
Native navigation; use a real destination |
| Name an input | <label htmlFor> |
Clear accessible name; requires a matching unique ID |
| Announce a changing result | role="status" |
Polite announcement; reserve it for useful updates |
| Describe a field error | aria-describedby |
Connects help to a field; IDs must stay unique |
What can go wrong
A styled <div onClick> may work for mouse users but cannot be reached with Tab or activated with Enter. Replace it with <button type="button">; the browser supplies its role, focus, and keyboard behavior.
If a changing status region announces every keystroke, screen-reader users hear a stream of interruptions. Announce meaningful results such as a save or updated count, and keep field-level validation beside its control instead of using a live region for every edit.
Common mistakes
- Tab through the page; check visible focus and sensible order.
- Activate controls by keyboard, including Enter and Space.
- Confirm each input has a visible connected label.
- Check errors identify the field and status updates do not steal focus.
- Test browser zoom and a screen reader when possible.
- Check for missing names or invalid ARIA in the accessibility tree.
Security and privacy
Accessibility does not make submitted text safe. Validate values before using them, and rely on React’s normal text rendering rather than injecting user content with dangerouslySetInnerHTML. If raw HTML is required, sanitize it with a suitable allowlist. Do not send typed field contents to analytics as a way to measure form errors.
Observability
- Track client exceptions and failed submissions by form and error category.
- Include a request ID for server-side submission failures.
- Never log field values, passwords, or other private input.
Checklist
- Choose semantic elements: buttons for actions, links for navigation.
- Connect labels and descriptions to form controls with IDs.
- Preserve visible keyboard focus and test the whole flow without a mouse.
- Announce dynamic status changes without moving focus unnecessarily.
- Validate user input; accessibility attributes do not provide security checks.
Interview questions
htmlFor help an input?id. Assistive technology gets the field's name, and clicking the label focuses the control.
- Match the label's
htmlForto the input's uniqueid. - Placeholder text alone is not a replacement for a label.
- Do not restate the role already provided by a button.
- Prefer the native element and behavior first.
- Keep the browser outline or provide a clear replacement.
- Check the contrast and visibility of focus styles.
- Tab and Shift+Tab move between focusable elements.
- Test interaction without relying on a pointer.
- A completed save or result count can be useful.
- Avoid announcing every keystroke or render.
- Reference the message with
aria-describedby. - Set
aria-invalidwhen the current field is invalid.
- Validate values before using or storing them.
- Do not log private field contents for analytics.
Further reading
- Controlled inputs and forms covers typed values and validation in React forms.
- Component and interaction testing shows how to check visible behavior and keyboard interaction.
- Styling React components and importing assets covers focus styling and asset choices.
- Read the W3C’s form labels tutorial and WCAG guidance on keyboard accessibility.
Conclusion
Run the empty and successful submission cases by keyboard and check the label, hint, error, and status with a screen reader. Then use Testing React Components and User Interactions to cover those behaviors in React tests, and Controlled Inputs and Forms for related form-state patterns.
Category
Related Posts
Testing React Components and User Interactions
Write behavior-first React tests with accessible roles, realistic user events, and async assertions while avoiding brittle checks of implementation details.
Vite Development Workflow for React and TypeScript
Learn a practical Vite workflow for React and TypeScript: create a project, use hot reload, build, preview, and protect environment values.
Advanced React State: When Local State Stops Fitting
Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.