Blog>
Snippets

Enhancing User Experience with Tooltips and Zoom Features

Illustrate how to implement interactive features such as tooltips and zoom capabilities in charts created with TanStack React Charts, improving data readability.
import { Chart } from 'react-charts';
import ReactTooltip from 'react-tooltip';

function MyChart() {
  const data = React.useMemo(
    () => [
      {
        label: 'Series 1',
        data: [{ primary: 'Jan', secondary: 10 }, { primary: 'Feb', secondary: 20 }]
      },
    ],
    []
  );

  const series = React.useMemo(
    () => ({
      type: 'bar'
    }),
    []
  );

  const axes = React.useMemo(
    () => [
      { primary: true, type: 'ordinal', position: 'bottom' },
      { type: 'linear', position: 'left' }
    ],
    []
  );

  const getSeriesStyle = React.useCallback(
    () => ({
      transition: 'all .5s ease'
    }),
    []
  );

  const getDatumStyle = React.useCallback(
    (datum) => ({
      r: datum.focused ? 7 : datum.selected ? 5 : 3,
      fill: datum.focused ? 'red' : 'blue'
    }),
    []
  );

  const tooltip = React.useMemo(
    () => ({
      render: ({ datum }) => datum ? `${datum.seriesLabel}: ${datum.primary} - ${datum.secondary}` : '',
    }),
    []
  );

  return (
    <div data-tip='' data-for='chartTooltip'>
      <ReactTooltip id='chartTooltip' place='top' effect='solid' />
      <Chart data={data} series={series} axes={axes} getSeriesStyle={getSeriesStyle} getDatumStyle={getDatumStyle} tooltip={tooltip} />
    </div>
  );
}
This code snippet demonstrates how to create a bar chart using TanStack React Charts with enhanced UX features such as interactive tooltips. The tooltips are displayed using 'react-tooltip' whenever a user hovers over a data point, showing detailed information about the data. Additionally, it customizes the data point's appearance (size and color) based on its focus and selection state, improving data readability and user interaction. The 'getSeriesStyle' and 'getDatumStyle' callbacks are used to dynamically style the series and data points.