How to create pie chart in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To create pie chart in react js, you have to use recharts package. It will create pie chart in react js.

Today, I am going to show you, how to create pie chart in react js.

Installation

Install the following packages to use recharts in react js.

npm

npm install recharts

yarn

yarn install recharts

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import { PieChart, Pie, Cell } from "recharts";

Step 3: Create a Component.

You can use <PieChart width={400} height={400}> to create pie chart in react js.

<PieChart width={400} height={400}>
    <Pie
      data={data}
      dataKey="value"
      cx="50%"
      cy="50%"
      outerRadius={100}
      fill="#8884d8"
      label
    >
      {data.map((entry, index) => (
        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
      ))}
    </Pie>
</PieChart>

Create pie chart example.

The below code is an example of a React. You have to import react and set <PieChart width={400} height={400}> to create pie chart in react js.

App.js

import { PieChart, Pie, Cell } from "recharts";

const data = [
  { name: "Group A", value: 400 },
  { name: "Group B", value: 300 },
  { name: "Group C", value: 300 },
  { name: "Group D", value: 200 },
];

const COLORS = ["#0088FE", "#00C49F", "#FFBB28", "#FF8042"];

const RechartsPie = () => (
  <PieChart width={400} height={400}>
    <Pie
      data={data}
      dataKey="value"
      cx="50%"
      cy="50%"
      outerRadius={100}
      fill="#8884d8"
      label
    >
      {data.map((entry, index) => (
        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
      ))}
    </Pie>
  </PieChart>
);

export default RechartsPie;

In the above code example, I have used the recharts package to create pie chart in react js.

Check the output of the above code.

React, create, pie, chart

All the best πŸ‘