Blog>
Snippets

Customizing Axes in TanStack React Charts

Provides an example of how to customize the axes of a TanStack React Chart, including changing the tick format and the labels for better readability.
import { Chart } from '@tanstack/react-charts';
import React from 'react';
First, import the Chart component from the @tanstack/react-charts package and React.
function MyChart({ data }) {
  const primaryAxis = React.useMemo(
    () => ({
      getValue: datum => datum.x,
      elementType: 'line',
      formatters: {
        scale: value => new Date(value).getFullYear(),
        tooltip: value => `Year: ${new Date(value).getFullYear()}`
      }
    }),
    []
  );
Define a primaryAxis with useMemo for optimizing performance. This defines how the x-values (dates) will be formatted for the scale and tooltips.
const secondaryAxes = React.useMemo(
    () => [{
      getValue: datum => datum.y,
      elementType: 'line',
      formatters: {
        scale: value => `$${value}`, // Prefixing dollar sign for monetary values.
        tooltip: value => `Value: $${value}`
      }
    }],
    []
  );
Define secondaryAxes with useMemo. This customizes the y-axis formatting, adding a dollar sign for monetary values, both in the chart scale and tooltips.
return (
    <Chart
      options={{
        data,
        primaryAxis,
        secondaryAxes
      }}
    />
  );
}
Render the Chart component with customized axes by passing data, primaryAxis, and secondaryAxes into the Chart's options.
export default MyChart;
Finally, export the MyChart component for use in other parts of the application.