If you're working with ReactJS and want to bring data to life with charts, Recharts offers a great way to create stunning visualizations with ease. In this guide, we’ll use Recharts and Fakestore API to fetch and display product data in a bar chart and a pie chart.
You can also check github . Lets get started!
🛠️ Setup: Starting with Vite
First, let’s create a new React app using Vite.
- Install Vite with the following command:
npm create vite@latest
Follow the prompts:
Project name:charts
Framework:React
Variant:JavaScript
Move to your project folder, install dependencies, and start the server:
cd charts
npm install
npm run dev
With your project running, let's create two components: one for a Product Price Bar Chart and another for a Product Categories Pie Chart.
📊 Step 1: Creating the Product Price Bar Chart (ProductChart.jsx)
In this component, we’ll fetch product data from the API and visualize it with a bar chart.
Code
Create a file in src/components/ProductChart.jsx with the following code:
// src/components/ProductChart.jsx
import React from 'react';
import axios from 'axios';
import { useState, useEffect } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
export default function ProductChart() {
const [products, setProducts] = useState([]);
const fetchData = async () => {
try {
const response = await axios.get('https://fakestoreapi.com/products');
setProducts(response.data);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
fetchData();
}, []);
// Prepare data for chart
const chartData = products.map(item => ({
name: item.id,
price: item.price,
}));
return (
<>
<div className='product'>
<h3 className='product-heading'>PRODUCT PRICE BAR CHART</h3>
<ResponsiveContainer width='95%' height={450}>
<BarChart
data={chartData}
margin={{
top: 5,
right: 30,
left: 20,
bottom: 20,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" label={{ value: "Product ID", position: "bottom", offset: -5 }} />
<YAxis label={{ value: "Price", angle: -90, position: "insideLeft", offset: -10 }} />
<Tooltip />
<Bar dataKey="price" fill="#eca1ac" />
</BarChart>
</ResponsiveContainer>
</div>
</>
);
}
Explanation
ResponsiveContainer: Makes the chart responsive by setting its width to 95% and height to 450px.
BarChart: The main component that renders the bar chart.
CartesianGrid: Adds a background grid for readability.
XAxis&YAxis: Set up the labels for product ID and price.
Tooltip: Shows data when hovering over the bars.
Bar: Renders the bars, with each bar representing a product price.
🖥️ Step 3: Rendering Components in App.js
To see your charts in action, you need to render these components in App.js.
Code
Update src/App.js as follows:
// src/App.js
import React from 'react'
import ProductChart from './components/ProductChart'
import './app.css'
import CategoryChart from './components/CategoryChart'
export default function App() {
return (
<div className='app'>
<ProductChart/>
<CategoryChart/>
</div>
)
}
With this in place, you should see both the bar chart and pie chart on your screen!
🎉 Conclusion
Congratulations! You've successfully used Recharts to create dynamic and responsive data visualizations in a React app. We’ve covered:
- Setting up a React project with Vite
- Fetching and processing data from Fakestore API
- Creating bar and pie charts using Recharts
Recharts makes building interactive visualizations simple and customizable. Experiment with other chart types and data sources to create even more engaging visualizations!
SOCIAL SHARE CARD GENERATOR