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 repository and live demo. 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
-
Project name:
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 2: Creating the Product Categories Pie Chart (CategoryChart.jsx
)
In this component, we’ll fetch product data, count the products in each category, and visualize them using a pie chart.
Code
Create a file in src/components/CategoryChart.jsx
with the following code:
// src/components/CategoryChart.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { PieChart, Pie, Tooltip, Cell, ResponsiveContainer, Legend } from 'recharts';
export default function CategoryChart() {
const [chartData, setChartData] = useState([]);
const fetchData = async () => {
try {
const response = await axios.get('https://fakestoreapi.com/products');
categoryCount(response.data);
} catch (err) {
console.log(err);
}
};
const categoryCount = (products) => {
const count = {};
products.forEach((product) => {
if (count[product.category]) {
count[product.category]++;
} else {
count[product.category] = 1;
}
});
const chartData = Object.keys(count).map((category) => ({
name: category,
value: count[category],
}));
setChartData(chartData);
};
useEffect(() => {
fetchData();
}, []);
const COLORS = ['#f9cdd4', '#eca1ac', '#e27589', '#b25b6e', '#7c3042'];
return (
<div>
<h3 className='product-heading'>PRODUCT CATEGORIES PIE CHART</h3>
<ResponsiveContainer width='80%' height={450}>
<PieChart>
<Pie
data={chartData}
cx="45%"
cy="50%"
outerRadius={200}
fill="#8884d8"
dataKey="value"
>
{chartData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip />
<Legend layout="vertical" align="right" verticalAlign="middle"/>
</PieChart>
</ResponsiveContainer>
</div>
);
}
Explanation
-
categoryCount
Method: Counts the number of products in each category and formats the result for display in the pie chart. -
PieChart
&Pie
: The main components that render the pie chart. -
Cell
: Adds color to each pie slice, defined by theCOLORS
array. -
cx
,cy
, andouterRadius
: Position and size the pie chart within the container.
🖥️ 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!
Top comments (0)