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!
First, let’s create a new React app using Vite.
npm create vite@latest
Follow the prompts:
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.
In this component, we’ll fetch product data from the API and visualize it with a bar chart.
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> </> ); }
In this component, we’ll fetch product data, count the products in each category, and visualize them using a pie chart.
Create a file in src/components/CategoryChart.jsx with the following code:
npm create vite@latest
To see your charts in action, you need to render these components in App.js.
Update src/App.js as follows:
cd charts npm install npm run dev
With this in place, you should see both the bar chart and pie chart on your screen!
Congratulations! You've successfully used Recharts to create dynamic and responsive data visualizations in a React app. We’ve covered:
Recharts makes building interactive visualizations simple and customizable. Experiment with other chart types and data sources to create even more engaging visualizations!
The above is the detailed content of Mastering Recharts: A Comprehensive Guide to Creating Charts in ReactJS. For more information, please follow other related articles on the PHP Chinese website!