Enhancing Accessibility in React Charts
Provide examples on improving the accessibility of TanStack React Charts, focusing on practices like adding proper aria-labels and keyboard navigation for users with disabilities.
import { Chart } from 'tanstack/react-charts';
function AccessibleChart({ data }) {
// Render chart with proper ARIA attributes
return (
<div tabIndex={0} aria-label='Interactive data chart' role='region'>
<Chart
options={{
data,
ariaLabel: 'Description of dataset',
ariaLabelledBy: 'ID_OF_TITLE_ELEMENT',
ariaDescribedBy: 'ID_OF_DESC_ELEMENT'
}}
/>
</div>
);
}
export default AccessibleChart;
This code snippet demonstrates how to enhance the accessibility of TanStack React Charts by wrapping the Chart component within a div that is focusable (tabIndex={0}) and providing it with an 'aria-label'. Inside the Chart, we use options to include ariaLabel, ariaLabelledBy, and ariaDescribedBy to describe the data and chart purpose for screen readers.
document.addEventListener('keydown', (event) => {
// Check for specific keys (e.g., arrows) to navigate the chart
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
// Implement your logic to shift focus or data point in the chart
alert('Change data point focus');
}
});
This piece of code adds keyboard navigation to the chart by listening to keydown events on the document. When the left or right arrow keys are pressed, an alert is triggered as a placeholder for the logic that would shift focus or highlight a different data point in the chart. In a real application, you would replace the alert with functionality to navigate the chart data points.