The recharts.js is a redefined chart library built with React and D3. It helps in creating interactive line graphs, bar graphs, pie graphs, etc. One of the main principles of it is that all its components are independent, lightweight, and can be deployed easily.
Creating React Application and Installing Module
-
Step 1: Create a React application using the following command:
npx create-react-app foldername
-
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
-
Step 3: Now move to the command line and install the rechart.js library
npm install recharts
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. We will generate a simple line chart using components from the library and JS data, using Class base Component
App.js
import React from "react" ; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, } from "recharts" ; const data = [ { name: "Block A" , l1: 4000, l2: 2400, amt: 2400, }, { name: "Block B" , l1: 3000, l2: 1398, amt: 2210, }, { name: "Block C" , l1: 2000, l2: 9800, amt: 2290, }, { name: "Block D" , l1: 2780, l2: 3908, amt: 2000, }, ]; export default function App() { return ( <div style={{ width: "1100px" , height: "600px" , backgroundColor: "black" }}> <ResponsiveContainer width= "100%" height= "100%" > <LineChart width={500} height={300} data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray= "3 3" /> <XAxis dataKey= "name" /> <YAxis /> <Tooltip /> <Legend /> <Line type= "monotone" dataKey= "l2" stroke= "#8884d8" activeDot={{ r: 8 }} /> <Line type= "monotone" dataKey= "l1" stroke= "#82ca9d" /> </LineChart> </ResponsiveContainer> </div> ); } |
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.