Blog>
Snippets

Initializing TanStack React Chart in React Application

Shows how to set up and render a basic line chart using TanStack React Charts in a React component.
import React from 'react';
import { Chart } from '@tanstack/react-charts';
Import React and the Chart component from the @tanstack/react-charts package.
const MyLineChart = () => {
  // Sample data
  const data = React.useMemo(() => [{
    label: 'Series 1',
    data: [{ primary: 1, secondary: 10 }, { primary: 2, secondary: 20 }, { primary: 3, secondary: 30 }]
  }], []);
Define a functional component and set up the chart data using the useMemo hook for performance optimization.
const axes = React.useMemo(() => [
    { primary: true, type: 'linear', position: 'bottom' },
    { type: 'linear', position: 'left' }
  ], []);
Set up the axes for the chart, marking one as primary, with both axes having linear scales.
return (
    <div style={{ height: '300px' }}>
      <Chart data={data} axes={axes} primaryCursor secondaryCursor tooltip />
    </div>
  );
};
Render the chart in a div container, passing the data and axes as props. The primaryCursor, secondaryCursor, and tooltip props enable interactive features.
export default MyLineChart;
Export the component for use in other parts of the application.