Blog>
Snippets

Initializing TanStack React Charts in a React Application

Show how to set up TanStack React Charts in a React project, including installing the package and basic configuration.
// Install TanStack React Charts using npm
npm install @tanstack/react-charts
This first step installs the TanStack React Charts package in your project using npm. Ensure you run this command inside your project directory in your terminal.
import { Chart } from '@tanstack/react-charts';
import React from 'react';
In the component where you want to use the chart, import the Chart component from the @tanstack/react-charts package, along with React for creating the component.
function MyChartComponent() {
  const data = React.useMemo(
    () => [
      {
        label: 'Series 1',
        data: [{ primary: 'A', secondary: 10 }, { primary: 'B', secondary: 20 }]
      }
    ],
    []
  );
  
  const primaryAxis = React.useMemo(
    () => ({
      getValue: datum => datum.primary
    }),
    []
  );
  
  const secondaryAxes = React.useMemo(
    () => [{
      getValue: datum => datum.secondary
    }],
    []
  );
  
  return (
    <Chart
      options={{
        data,
        primaryAxis,
        secondaryAxes
      }}
    />
  );
}
Defines a React component 'MyChartComponent' that renders a basic chart using TanStack React Charts. It includes sample data and configurations for primary and secondary axes. 'useMemo' is used for performance optimization, ensuring these configurations are calculated only when necessary.