How to create bar chart in react js?

Hi Friends πŸ‘‹,

Welcome To aGuideHub!

To create a bar chart in React js, you have to use the bar component and react-chartjs-2. It will create a bar chart in react js.

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

Table of contents

  • Set up your project.
  • Import necessary components.
  • Set up data.

Let’s start with the first step.

Step 1: Set up your project.

To create a React JS app, you have to install create-react-app and then install chart.js and react-chartjs-2 as required.

Step 2: Import necessary components.

The Bar component will create the actual bar chart. import the necessary components from react-chartjs-2.

import { Bar } from 'react-chartjs-2';

Step 3: Set up data.

Set up your data, then use the Array object. it has to make labels, data, and background color.

export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: [74, 47, 475],
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
    },
    {
      label: 'Dataset 2',
      data: [74, 47, 475],
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

ReactJS create bar chart example.

The below code is an example of, This code is a React component that renders a chart at once using the chart.js library.

App.js

import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: 'Chart.js Bar Chart',
    },
  },
};

const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: [74, 47, 475],
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
    },
    {
      label: 'Dataset 2',
      data: [74, 47, 475],
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

export default function App() {
  return <Bar options={options} data={data} />;
}

Check the output of the above code example.

React, bar-chart

Here, we are provided code sandbox links for the above program create bar chart in React js. Then you can use whenever you went and do the changes as per your requirements.

Try it Yourself

All the best πŸ‘

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts