Home  >  Article  >  Web Front-end  >  Mastering Recharts: A Comprehensive Guide to Creating Charts in ReactJS

Mastering Recharts: A Comprehensive Guide to Creating Charts in ReactJS

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-07 11:41:02325browse

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.

  1. Install Vite with the following command:
   npm create vite@latest
  1. Follow the prompts:

    • Project name: charts
    • Framework: React
    • Variant: JavaScript
  2. 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.

Mastering Recharts: A Comprehensive Guide to Creating Charts in ReactJS

? 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:

   npm create vite@latest

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 the COLORS array.
  • cx, cy, and outerRadius: Position and size the pie chart within the container.

Mastering Recharts: A Comprehensive Guide to Creating Charts in ReactJS

?️ 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:

   cd charts
   npm install
   npm run dev

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!

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn