Blog>
Snippets

Creating a Basic Pie Chart

Demonstrate how to construct a simple pie chart using TanStack React Charts library, including setting up the dataset and configuring the pie chart options for a basic visual representation.
import { Chart } from 'react-charts'
Imports the Chart component from the react-charts library.
function MyChart() {
  const data = React.useMemo(
    () => [
      {
        label: 'Series 1',
        data: [{ primary: 'A', secondary: 10 }, { primary: 'B', secondary: 20 }]
      }
    ],
    []
  );
Defines a component function and uses React's useMemo hook to memoize the dataset, which includes labels and data points for our pie chart.
const series = React.useMemo(
    () => ({
      type: 'pie'
    }),
    []
  );
Uses React's useMemo hook to define the series type as 'pie' for rendering a pie chart.
const axes = React.useMemo(
    () => [
      { primary: true, type: 'ordinal', position: 'left' },
      { type: 'linear', position: 'bottom' }
    ],
    []
  );
Memoizes the axes configuration. Although not directly used in pie charts, it's part of the chart configuration.
return (
    <Chart data={data} series={series} axes={axes} tooltip />
  );
}
Renders the Chart component with our data, series, and axes configurations along with enabling the tooltip.
export default MyChart;
Exports the MyChart component for use in other parts of the application.