Creating an accessible (a11y-compatible) button group component in React with TypeScript involves ensuring that the component adheres to accessibility best practices. This includes proper keyboard navigation, focus management, ARIA roles, and semantic HTML.
Below is a well-structured implementation of an accessible button group component:
Button Group Component
import React, { useState, useRef, useEffect, KeyboardEvent } from 'react';
interface ButtonGroupProps {
buttons: string[]; // Array of button labels
onButtonClick: (index: number) => void; // Callback for button click
selectedButtonIndex?: number; // Index of the currently selected button
}
const ButtonGroup: React.FC<ButtonGroupProps> = ({
buttons,
onButtonClick,
selectedButtonIndex = -1,
}) => {
const [focusedIndex, setFocusedIndex] = useState<number>(selectedButtonIndex);
const buttonRefs = useRef<Array<HTMLButtonElement | null>>([]);
useEffect(() => {
// Ensure the focused index is updated when the selected button changes
if (selectedButtonIndex !== -1) {
setFocusedIndex(selectedButtonIndex);
}
}, [selectedButtonIndex]);
const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
switch (event.key) {
case 'ArrowRight':
event.preventDefault();
setFocusedIndex((prevIndex) => (prevIndex + 1) % buttons.length);
break;
case 'ArrowLeft':
event.preventDefault();
setFocusedIndex((prevIndex) =>
prevIndex === 0 ? buttons.length - 1 : prevIndex - 1
);
break;
case 'Home':
event.preventDefault();
setFocusedIndex(0);
break;
case 'End':
event.preventDefault();
setFocusedIndex(buttons.length - 1);
break;
default:
break;
}
};
useEffect(() => {
// Focus the currently focused button
if (buttonRefs.current[focusedIndex]) {
buttonRefs.current[focusedIndex]?.focus();
}
}, [focusedIndex]);
return (
<div role="group" aria-label="Button Group">
{buttons.map((label, index) => (
<button
key={index}
ref={(el) => (buttonRefs.current[index] = el)}
onClick={() => onButtonClick(index)}
onKeyDown={(event) => handleKeyDown(event, index)}
onFocus={() => setFocusedIndex(index)}
aria-pressed={index === selectedButtonIndex} // Indicates the selected state
tabIndex={index === focusedIndex ? 0 : -1} // Manage focusability
className={`button ${index === selectedButtonIndex ? 'selected' : ''}`}
>
{label}
</button>
))}
</div>
);
};
export default ButtonGroup;
Explanation of Key Features
-
ARIA Roles and Attributes:
- The
role="group" attribute is added to the container div to indicate that the buttons are part of a logical group.
- The
aria-label="Button Group" provides a label for screen readers to describe the purpose of the group.
- The
aria-pressed attribute indicates whether a button is selected (true/false).
-
Keyboard Navigation:
- Users can navigate between buttons using the
ArrowLeft, ArrowRight, Home, and End keys.
- The
handleKeyDown function ensures smooth navigation and wraps around the edges of the button group.
-
Focus Management:
- The
tabIndex attribute ensures only the currently focused button is focusable (tabIndex={0}), while others are not (tabIndex={-1}).
- The
useEffect hook ensures that the focused button receives focus programmatically when the focusedIndex changes.
-
Dynamic Styling:
- The
className dynamically applies a selected class to the currently selected button, allowing for visual feedback.
-
TypeScript Integration:
- The
ButtonGroupProps interface ensures type safety for props like buttons, onButtonClick, and selectedButtonIndex.
Usage Example
import React from 'react';
import ButtonGroup from './ButtonGroup';
const App: React.FC = () => {
const [selectedIndex, setSelectedIndex] = React.useState<number>(-1);
const handleButtonClick = (index: number) => {
setSelectedIndex(index);
console.log(`Button ${index} clicked`);
};
return (
<div>
<h1>Select an Option</h1>
<ButtonGroup
buttons={['Option 1', 'Option 2', 'Option 3']}
onButtonClick={handleButtonClick}
selectedButtonIndex={selectedIndex}
/>
</div>
);
};
export default App;
Styling Suggestions
You can add CSS to style the buttons and highlight the selected one:
.button {
padding: 10px 20px;
margin: 5px;
border: none;
background-color: #f0f0f0;
cursor: pointer;
outline: none;
}
.button:hover {
background-color: #e0e0e0;
}
.button.selected {
background-color: #007bff;
color: white;
}
Accessibility Checklist
This implementation ensures that the button group is fully accessible and user-friendly for both keyboard and screen reader users.
Final Answer: The code above provides a complete, accessible, and reusable button group component in React with TypeScript.