Create a Pie Chart in Next.js

Tosin Moronfolu

The pie chart is one of the most effective ways of illustrating data and they have been around since the 1800s. A pie chart is a circular graph showing statistical information in numerical proportion. Pie charts are used widely in analyzing business and media data.

At the end of the article, you will have understood how to implement a pie chart into your Next.js application.

Prerequisites

A basic understanding of Next.js is needed to follow along with this article.

Repository

You can find the complete code used in this article on GitHub:

https://github.com/folucode/nextjs-pie-chart

Sandbox

The completed project is on CodeSandbox. Fork it and run the code.

Project Setup

Node has to be installed on your computer to set up the Next.js application. To install Node, go to the Nodejs website and follow the instructions to install the software compatible with your operating system.

You can verify the Node.js installation by running the command below:

1node -v
2v16.10.0 //node version installed

To create the Next.js app, run the command below. It will automatically set up a boilerplate Next.js app.

npx stands for Node Package Execute. It executes any package from the npm registry without installing it.

1npx create-next-app@latest <app-name>
2# or
3yarn create next-app <app-name>

After the installation is complete, change the directory into the app you just created:

1cd <app-name>

Run npm run dev or yarn dev to start the development server on http://localhost:3000.

Create pie chart

You'll be using an npm package called [Chart.js](https://www.npmjs.com/package/chart.js) to create the pie chart in this application. Install it using the command below:

1$ npm i chart.js

After installation is complete, open the index.js file in the pages folder and replace the boilerplate code with the code below:

1import Chart from 'chart.js/auto';
2import { useRef, useEffect } from 'react';
3
4export default function Home() {
5 const canvas = useRef();
6
7 useEffect(() => {}, [])
8
9 return (
10 <div className='container'>
11 <canvas ref={canvas}></canvas>
12 </div>
13 );
14}

In the code above, the Chart.js package is first imported. useRef and useEffect hooks are both imported from the react package. The useRef hook creates a reference, and it is then assigned to the ref property on the canvas element. Subsequently, all the canvas element's available properties and methods will be on the .current property of the ref.

In the useEffect hook, between the curly braces of the arrow function, paste the following code, which will take in a set of configurations and create the pie chart:

1import Chart from 'chart.js/auto';
2import { useRef, useEffect } from 'react';
3export default function Home() {
4 ...
5 useEffect(() => {
6 const ctx = canvas.current;
7
8 let chartStatus = Chart.getChart('myChart');
9 if (chartStatus != undefined) {
10 chartStatus.destroy();
11 }
12
13 const chart = new Chart(ctx, {
14 type: 'pie',
15 data: {
16 labels: ['Lions', 'Monkeys', 'Zebras', 'Eagles', 'Horses'],
17 datasets: [
18 {
19 label: 'Dataset 1',
20 data: [12, 19, 3, 2, 3],
21 backgroundColor: [
22 'rgba(255, 99, 132, 0.2)',
23 'rgba(54, 162, 235, 0.2)',
24 'rgba(255, 206, 86, 0.2)',
25 'rgba(75, 192, 192, 0.2)',
26 'rgba(153, 102, 255, 0.2)',
27 'rgba(255, 159, 64, 0.2)',
28 ],
29 borderColor: [
30 'rgba(255, 99, 132, 1)',
31 'rgba(54, 162, 235, 1)',
32 'rgba(255, 206, 86, 1)',
33 'rgba(75, 192, 192, 1)',
34 'rgba(153, 102, 255, 1)',
35 'rgba(255, 159, 64, 1)',
36 ],
37 borderWidth: 1,
38 },
39 ],
40 },
41 options: {
42 responsive: true,
43 plugins: {
44 legend: {
45 position: 'top',
46 },
47 title: {
48 display: true,
49 text: 'Number of animals in the zoo',
50 },
51 },
52 },
53 });
54 }, []);
55 ...
56}
  1. The canvas element is assigned to a variable called ctx. A check is done to ensure a Chart hasn't been created already. If a Chart already exists, it is then destroyed to create a new Chart. If the previous one isn't destroyed, it will prevent the initialization and creation of a new Chart object.
  2. A new Chart object is then initialized, which takes in two parameters, the canvas element you want to render the chart on and a set of configurations for how the pie chart will display. The chart type is set to 'pie' in the configuration object.
  3. There is a data property where several other configs are set, including labels for the chart, datasets used to define the specific data to be shown, and the background color to distinguish one dataset from another. It also contains a border-color property and border width to set the border's thickness.
  4. There is an options object to define the responsiveness of the chart, it's positioning, and title.

Rendering the Pie Chart

In the globals.css file in the styles folder, replace the boilerplate code with the code below:

1html,
2body {
3 padding: 0;
4 margin: 0;
5 font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
6 Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
7}
8
9.container {
10 position: relative;
11 margin: auto;
12 height: 50vh;
13 width: 50vw;
14}

This code above aligns the parent container of the canvas element to the center of the page.

After successfully following the steps above, run the command below in your terminal:

1$ npm run dev

The above command will spin up a development server on http://localhost:3000, which you can use to view the application. Check the image below to see the outcome:

You can hover over the pie sections to get more information about each section.

Conclusion

This article showed you how to create pie charts in Next.js applications using chart.js.

Resources

You may find these resources helpful:

Tosin Moronfolu

Software Engineer

I'm a software engineer with hands-on experience in building robust and complex applications improving performance and scalability. I love everything tech and science, especially physics and maths. I also love to read books, mainly non-fiction, and I love music; I play the guitar.