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.

published: reading time: 8 min read author: Geek Workbench updated: November 3, 2026
Quick Summary

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

  1. 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.
  2. 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.
  3. 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

1. Why should an action use a button instead of a clickable div?
A button already has the right semantics, tab focus, and keyboard activation. A div needs extra role, focus, and key handling, which is easy to implement inconsistently.
2. How does htmlFor help an input?
It connects a label to the input with the matching id. Assistive technology gets the field's name, and clicking the label focuses the control.
3. When should a React component use a status region?
Use a status region for useful updates that appear without a page change, such as a successful save or updated result count. Avoid announcing every small render.
4. Why should a label be visible and connected to its input?
The association gives the control a clear name and makes the label clickable.
  • Match the label's htmlFor to the input's unique id.
  • Placeholder text alone is not a replacement for a label.
5. When should ARIA be added to a native control?
Add ARIA when HTML alone cannot express a needed name, state, or relationship.
  • Do not restate the role already provided by a button.
  • Prefer the native element and behavior first.
6. What makes a keyboard focus indicator important?
It shows keyboard users which control will receive the next action.
  • Keep the browser outline or provide a clear replacement.
  • Check the contrast and visibility of focus styles.
7. Which keys commonly activate a button?
Enter and Space activate a native button.
  • Tab and Shift+Tab move between focusable elements.
  • Test interaction without relying on a pointer.
8. When should a live region announce an update?
Use one for a meaningful change that occurs without navigation or focus movement.
  • A completed save or result count can be useful.
  • Avoid announcing every keystroke or render.
9. Where should a field validation error be connected?
Associate the error text with the relevant field.
  • Reference the message with aria-describedby.
  • Set aria-invalid when the current field is invalid.
10. Does an accessible form make its input safe?
No. Accessibility and input security solve different problems.
  • Validate values before using or storing them.
  • Do not log private field contents for analytics.

Further reading

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.

#react #typescript #testing

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.

#vite #react #typescript

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.

#react #typescript #state-management