Blog>
Snippets

Initializing TanStack React Chart in a React Component

Shows how to set up a basic TanStack React Chart within a functional React component, including the installation steps and the initial chart rendering process.
// Step 1: Install the package
// Run `npm install @tanstack/react-charts` in your project directory
First, you need to install the TanStack React Charts library using npm or yarn to use it in your project.
import { Chart } from '@tanstack/react-charts';
import React from 'react';
Import the Chart component from the @tanstack/react-charts package along with React to begin using it.
function MyChart() {
  // Sample data for the chart
  const data = React.useMemo(
    () => [
      {
        label: 'Series 1',
        data: [
          { primary: 'A', secondary: 10 },
          { primary: 'B', secondary: 20 },
          { primary: 'C', secondary: 30 }
        ]
      }
    ],
    []
  );

  // Options for the chart
  const options = React.useMemo(
    () => ({
      data,
      primaryAxis: {
        getValue: datum => datum.primary
      },
      secondaryAxes: [
        {
          getValue: datum => datum.secondary
        }
      ]
    }),
    [data]
  );

  return <Chart options={options} />;
}

export default MyChart;
Define a functional component called MyChart where you use the Chart component. This component includes a sample dataset and options for configuring the primary and secondary axes. Finally, it renders the Chart component with the provided options.