Adding Interactivity to TanStack React Charts
A code snippet to add hover effects and tooltips to a chart for enhancing user interaction.
import { Chart } from 'tanstack-react-charts';
function MyInteractiveChart() {
const data = useChartData(); // Assuming useChartData is a custom hook for fetching chart data
// Custom tooltip component
const TooltipComponent = ({ datum }) => (
<div style={{ padding: '10px', backgroundColor: 'rgba(0,0,0,0.6)', color: '#fff' }}>
{datum.primary}: {datum.secondary}
</div>
);
return (
<Chart
options={{
data: data,
initialWidth: 800,
initialHeight: 600,
tooltip: {
render: TooltipComponent, // Use the custom tooltip component
},
interactionMode: 'closest',
}}
/>
);
}
This code sets up a TanStack React Chart with a custom tooltip. The TooltipComponent renders a simple styled div showing the primary (usually the x value) and secondary (usually the y value) data points when hovered over a chart segment. The 'interactionMode' is set to 'closest', making the tooltip appear for the closest datapoint to the mouse cursor.