Blog>
Snippets

Customize Chart Tooltip with Function Components

Provide an example of customizing a chart's tooltip using a React functional component, enhancing the interactivity and visual appeal of the chart.
import React from 'react';
import {Chart} from 'tanstack-react-charts';
Import necessary modules from React and TanStack React Charts.
const CustomTooltip = ({tooltipData}) => (
  <div style={{padding: '10px', background: 'rgba(0,0,0,0.6)', color: 'white'}}>
    {tooltipData && `${tooltipData.label}: ${tooltipData.value}`}
  </div>
);
Define a React functional component for a custom tooltip. This component receives tooltipData as a prop and renders a styled div element displaying the label and value.
const MyChartComponent = () => {
  const data = React.useMemo(() => [
    {label: 'Data Point 1', data: [{primary: 1, secondary: 10}]},
    {label: 'Data Point 2', data: [{primary: 2, secondary: 20}]}
  ], []);

  return (
    <Chart
      options={{
        data,
        tooltip: {
          render: CustomTooltip
        }
      }}
    />
  );
};
Create a chart component using the CustomTooltip component for rendering tooltips. The data is defined using useMemo for performance optimization, and the Chart component from TanStack React Charts is configured to use the custom tooltip.
export default MyChartComponent;
Export the chart component for use in other parts of the application.