Focus Management Implementation for Accessibility
Focus Management is controlling which element has keyboard focus in dynamic interfaces. Incorrect focus makes SPAs unusable for screen reader and keyboard navigation users.
When to Manage Focus
- Opening/closing a modal window
- Navigating between pages in SPA
- Appearing/hiding dynamic content
- Completing a multi-step process (wizard)
- Removing an item from a list
- Form validation error notifications
Modal Window: Full Cycle
function useModal() {
const [isOpen, setIsOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const modalRef = useRef<HTMLDivElement>(null);
const open = useCallback(() => {
setIsOpen(true);
}, []);
const close = useCallback(() => {
setIsOpen(false);
// Return focus to element that opened the modal
triggerRef.current?.focus();
}, []);
// Move focus into modal on open
useEffect(() => {
if (isOpen) {
const firstFocusable = modalRef.current?.querySelector<HTMLElement>(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
firstFocusable?.focus();
}
}, [isOpen]);
return { isOpen, open, close, triggerRef, modalRef };
}
function DeleteConfirmation({ item }) {
const { isOpen, open, close, triggerRef, modalRef } = useModal();
return (
<>
<button ref={triggerRef} onClick={open}>
Delete {item.name}
</button>
{isOpen && (
<div
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
ref={modalRef}
>
<h2 id="modal-title">Confirm deletion</h2>
<p>Delete "{item.name}"? This action is irreversible.</p>
<button onClick={() => { deleteItem(item.id); close(); }}>
Delete
</button>
<button onClick={close}>Cancel</button>
</div>
)}
</>
);
}
SPA Navigation (React Router)
// useFocusOnNavigate.ts
export function useFocusOnNavigate() {
const location = useLocation();
useEffect(() => {
// Small delay — let React render new page
const timer = setTimeout(() => {
const main = document.getElementById('main-content');
if (main) {
main.focus();
main.scrollIntoView();
}
}, 50);
return () => clearTimeout(timer);
}, [location.pathname]);
}
Form Validation: Focus on First Error
function Form() {
const [errors, setErrors] = useState<Record<string, string>>({});
const firstErrorRef = useRef<HTMLElement | null>(null);
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
const validationErrors = validate(formData);
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors);
// Move focus to first field with error
const firstErrorField = document.querySelector('[aria-invalid="true"]');
(firstErrorField as HTMLElement)?.focus();
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
aria-invalid={!!errors.email}
aria-describedby={errors.email ? 'email-error' : undefined}
/>
{errors.email && (
<span id="email-error" role="alert">
{errors.email}
</span>
)}
</div>
</form>
);
}
Removing an Item from a List
function TodoList() {
const [items, setItems] = useState(initialItems);
const itemRefs = useRef<Record<number, HTMLButtonElement>>({});
const deleteItem = (id: number, index: number) => {
setItems(prev => prev.filter(item => item.id !== id));
// Move focus to next item, or previous if deleted last
setTimeout(() => {
const newItems = items.filter(item => item.id !== id);
const focusIndex = Math.min(index, newItems.length - 1);
if (focusIndex >= 0) {
itemRefs.current[newItems[focusIndex].id]?.focus();
}
}, 0);
};
return (
<ul>
{items.map((item, index) => (
<li key={item.id}>
{item.text}
<button
ref={el => { if (el) itemRefs.current[item.id] = el; }}
onClick={() => deleteItem(item.id, index)}
aria-label={`Delete: ${item.text}`}
>
×
</button>
</li>
))}
</ul>
);
}
useRef vs getElementById
Prefer useRef over document.getElementById in React — it's safer for SSR and testing.
Timeline
Basic focus management (modals, SPA navigation): 2–3 days. Complete system handling all patterns: 4–5 days.







