This article will teach us how to create a Bar chart in the React application.
Prerequisites of React
- Familiarity with HTML and JavaScript.
- node.js installed
Create React Project
To create a React app, use the following command in the terminal.
npx create-react-app matui
Install Bootstrap
Now install Bootstrap by using the following command.
npm install bootstrap
Now, open the index.js file and add the import Bootstrap.
import 'bootstrap/dist/css/bootstrap.min.css';
Install Recharts
Now Install Recharts by using the following command.
npm i recharts bootstrap
Now right-click on the src folder and create a new component named 'Barchartdemo.js'
import React from "react";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend
} from "recharts";
const data = [
{
name: "CSK",
UV: 40,
PV: 240,
amt: 240,
},
{
name: "GT",
UV: 30,
PV: 139,
amt: 221,
},
{
name: "RR",
UV: 20,
PV: 980,
amt: 229,
},
{
name: "MI",
UV: 27,
PV: 390,
amt: 200,
}
];
function BarChartdemo() {
return (
<div>
<BarChart
width={500}
height={300}
data={data}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 5
}}
>
<CartesianGrid />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="PV" fill="#8884d8" />
<Bar dataKey="UV" fill="#82ca9d" />
</BarChart>
</div>
);
}
export default BarChartdemo;
Now, import the Barchartdemo component in the src/App.js file.
import './App.css';
import BarChartdemo from './Barchartdemo'
function App() {
return (
<div className="App">
<BarChartdemo/>
</div>
);
}
export default App;
Now, run the project using the 'npm start' command and check the result.
Summary
This article provides a step-by-step guide on creating a bar chart in a React application using the Recharts library.