Lesson 4 of 8
Accessible Forms
Accessible forms aren't just nice-to-have - they're a legal requirement in many jurisdictions and improve UX for all users, including keyboard users and people on mobile. The key techniques: proper label associations, error announcement, focus management, and keyboard navigation.
Accessible Form Patterns
import { useId, useRef } from 'react';
// ---- FormField - accessible by design ----
interface FormFieldProps {
label: string;
type?: string;
error?: string;
hint?: string;
required?: boolean;
registration: object; // from react-hook-form register()
}
function FormField({ label, type = 'text', error, hint, required, registration }: FormFieldProps) {
const fieldId = useId();
const hintId = hint ? `${fieldId}-hint` : undefined;
const errorId = error ? `${fieldId}-error` : undefined;
const describedBy = [hintId, errorId].filter(Boolean).join(' ');
return (
<div className="form-field">
<label htmlFor={fieldId}>
{label}
{required && <span aria-label="required" style={{ color: 'red', marginLeft: 4 }}>*</span>}
</label>
{hint && <p id={hintId} style={{ fontSize: 13, color: '#666' }}>{hint}</p>}
<input
id={fieldId}
type={type}
required={required}
aria-invalid={!!error} // announces to screen readers that field is invalid
aria-describedby={describedBy || undefined}
{...registration}
/>
{/* role="alert" announces immediately when it appears */}
{error && (
<p id={errorId} role="alert" style={{ color: 'red', fontSize: 13, marginTop: 4 }}>
{error}
</p>
)}
</div>
);
}
// ---- Focus management ----
// Move focus to first error after failed submission
const { handleSubmit, setFocus, formState: { errors } } = useForm();
async function onInvalid() {
// Focus the first field with an error for keyboard users
const firstError = Object.keys(errors)[0] as keyof FormData;
if (firstError) setFocus(firstError);
}
<form onSubmit={handleSubmit(onSubmit, onInvalid)}>...</form>
// ---- Focus trap for modals ----
function useFocusTrap(containerRef: React.RefObject<HTMLElement>, isActive: boolean) {
useEffect(() => {
if (!isActive || !containerRef.current) return;
const focusable = containerRef.current.querySelectorAll<HTMLElement>(
'a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])'
);
const first = focusable[0];
const last = focusable[focusable.length - 1];
function handleKeyDown(e: KeyboardEvent) {
if (e.key !== 'Tab') return;
if (e.shiftKey) {
if (document.activeElement === first) { e.preventDefault(); last.focus(); }
} else {
if (document.activeElement === last) { e.preventDefault(); first.focus(); }
}
}
containerRef.current.addEventListener('keydown', handleKeyDown);
first?.focus(); // focus first element when modal opens
return () => containerRef.current?.removeEventListener('keydown', handleKeyDown);
}, [isActive]);
}
// ---- Skip link - keyboard navigation shortcut ----
function SkipLink() {
return (
<a
href="#main-content"
style={{
position: 'absolute', top: -40, left: 0,
background: '#229c6b', color: 'white', padding: '8px 16px',
transition: 'top 0.2s',
}}
onFocus={e => { (e.target as HTMLElement).style.top = '0'; }}
onBlur={e => { (e.target as HTMLElement).style.top = '-40px'; }}
>
Skip to main content
</a>
);
}Tip
Tip
Practice Accessible Forms in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Accessible Forms
Practice Task
Note
Practice Task - (1) Write a working example of Accessible Forms from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Accessible Forms is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?