Blog>
Snippets

Creating a Typed Chart Component

Demonstrate creating a basic chart component using TanStack React Charts with fully typed props and state, emphasizing type safety.
import { Chart } from '@tanstack/react-chart';
import React from 'react';
Import Chart component from TanStack React Charts and React.
interface ChartData {
  label: string;
  data: Array<{ primary: number; secondary: number }>;
}
Define TypeScript interface for chart data.
interface TypedChartProps {
  data: ChartData[];
}
Define TypeScript interface for the props of our chart component.
const TypedChart: React.FC<TypedChartProps> = ({ data }) => {
  const chartData = React.useMemo(() => data, [data]);
  const axes = React.useMemo(() => [
    { primary: true, type: 'linear', position: 'bottom' },
    { type: 'linear', position: 'left' }
  ], []);
  return <Chart data={chartData} axes={axes} />;
};
Create a functional chart component using TypedChartProps for props and rendering it with the Chart component.
export default TypedChart;
Export the TypedChart component for use in other parts of the application.