How to implement BarChart in ReactJS ?

In our React app sometimes we want to display a BarChart representation of a particular data. We can use react-chartjs-2 and chart.js module in ReactJS to display information in BarCharts format. Following are some simple steps to do so:
Step 1: Create a React application using the following command.
npx create-react-app BARCHART_REACT
Step 2: After creating your project folder i.e. BARCHART_REACT, move to it using the following command.
cd BARCHART_REACT
Step 3: After creating the ReactJS application, Install react-chartjs-2 and chart.js modules using the following command.
npm install --save react-chartjs-2 chart.js
Project structure:
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import { Bar } from "react-chartjs-2"; function App() { return ( <div className="App"> <h1>GEEKSFORGEEKS BAR CHART REACTJS</h1> <div style={{ maxWidth: "650px" }}> <Bar data={{ // Name of the variables on x-axies for each bar labels: ["1st bar", "2nd bar", "3rd bar", "4th bar"], datasets: [ { // Label for bars label: "total count/value", // Data or value of your each variable data: [1552, 1319, 613, 1400], // Color of each bar backgroundColor: ["aqua", "green", "red", "yellow"], // Border color of each bar borderColor: ["aqua", "green", "red", "yellow"], borderWidth: 0.5, }, ], }} // Height of graph height={400} options={{ maintainAspectRatio: false, scales: { yAxes: [ { ticks: { // The y-axis value will start from zero beginAtZero: true, }, }, ], }, legend: { labels: { fontSize: 15, }, }, }} /> </div> </div> ); } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:




