Loading content…
Loading content…
Refactor a non-accessible interactive component (a div-based toggle switch) to satisfy WCAG AA accessibility standards. The component must support keyboard navigation (Tab to focus, Space/Enter to toggle) and state announcements via ARIA properties.
Expected Output
An accessible React component utilizing semantic inputs or custom key handlers and ARIA attributes.
Click to toggle the recommended code solution
Architectural Explanation
The React component uses a button element with accessibility parameters. It binds click and keypress handlers, and toggles visual indicators with focus outlines.Code Snippet
import React, { useState } from "react";
export function AccessibleToggle() {
const [isChecked, setIsChecked] = useState(false);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
setIsChecked(!isChecked);
}
};
return (
<div className="flex items-center gap-3">
<span id="toggle-label" class="text-sm font-semibold">Notifications</span>
<button
type="button"
role="switch"
aria-checked={isChecked}
aria-labelledby="toggle-label"
onClick={() => setIsChecked(!isChecked)}
onKeyDown={handleKeyDown}
className={`w-12 h-6 rounded-full transition-colors relative focus:outline-none focus:ring-2 focus:ring-indigo-600 ${
isChecked ? "bg-indigo-600" : "bg-slate-300"
}`}
>
<span className={`block w-4 h-4 rounded-full bg-white transition-transform absolute top-1 ${
isChecked ? "translate-x-7" : "translate-x-1"
}`} />
</button>
</div>
);
}How to pitch this solution during technical interviews
I ensure accessibility by choosing native elements when possible. If custom elements are required, I add focus indicators, map state variables to ARIA roles, and bind keyboard event handlers.