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:
Prerequisite:
Approach to implement BarChart:
-
Importing React-ChartJS-2: Import the
Bar
component from the “react-chartjs-2” library. -
Creating a Bar Chart in React: Define a functional component
App
that returns a bar chart using the importedBar
component. Customize the chart by specifying data points, labels, colors, and other options. -
Rendering the Chart Component: Include the chart component within the JSX of the
App
component, setting attributes likedata
,height
, andoptions
to configure the appearance and behavior of the bar chart.
Steps to Create React Application:
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:
The updated dependencies in package.json file will look like:
"dependencies": {
"chart.js": "^4.4.1",
"react-chartjs-2": "^5.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Now write down the following code in the App.js file.
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/