Blog>
Snippets

Initializing TanStack React Charts in a React Component

Demonstrate the process of initializing a basic TanStack React Chart within a React functional component, focusing on the import and setup steps.
import { Chart } from 'react-chart-3';
import { Line } from 'react-chartjs-2';
Importing the necessary components from 'react-chart-3' and 'react-chartjs-2' libraries.
import React, { useState, useEffect } from 'react';
Import React along with useState and useEffect hooks for state management and side effects in a functional component.
const MyChartComponent = () => {
  const [chartData, setChartData] = useState({});
  useEffect(() => {
    // Fetch your chart data here and update state
    setChartData({
      labels: ['Jan', 'Feb', 'Mar'],
      datasets: [
        {
          label: 'Sales',
          data: [65, 59, 80],
          fill: false,
          backgroundColor: 'rgb(75,192,192)',
          borderColor: 'rgba(75,192,192,0.2)',
        },
      ],
    });
  }, []);
  return (
    <Line data={chartData} />
  );
};
Defines a functional component that initializes chart data state, fetches chart data within useEffect, and renders a Line chart with the fetched data.
export default MyChartComponent;
Exports the chart component for use in other parts of the application.