DEV Community

Cover image for How to Create a Chart in React With Recharts
Femi Akinyemi
Femi Akinyemi

Posted on

How to Create a Chart in React With Recharts

Introduction

Visualizing data has always been a vital component of software engineering, especially in the front-end development cycle. It is beneficial for our users to understand what is going on by visualizing data in our applications.

Recharts is a composable charting library built on React components. It makes integrating charts into our React application seamless and easy.

This article will show you how to use Recharts in a simple application using ReactJS.

We will create an application that pulls cryptocurrency prices from an API and displays them in a bar chart rather than making up our data chart.

With CoinCap's API, we'll be able to get real-time cryptocurrency prices for our React application.

Prerequisites

To follow along, you’ll need the following:

Setting up our React project

We will create our project following the step mentioned in step one above. Let's get started by running the following command:

npx create-react-app react-recharts-tutorial

We will now navigate to the project directory by running:

cd react-recharts-tutorial

I have chosen to name the project react-recharts-tutorial because we are learning how Recharts works in React.

Currently, this is how my project structure looks.

Folder structure

Installing Recharts into our React application

To install Recharts, we run the following command:

npm install recharts

It is essential to verify the dependencies in the package.json file to confirm whether Recharts has been installed.

This is the current state of my dependencies.




//...

  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "recharts": "^2.1.13",
    "web-vitals": "^2.1.4"
  },

  //...




Enter fullscreen mode Exit fullscreen mode

React code cleanup

The create react app command bootstraps a React application quickly, but we need to modify it to fit our use case since we don't need all the features it provides.
In this case, we do not need App.css or logo.svg inside the src folder. We can delete all the code in App.js.

Fetching the data

In App.js, we'll get the data from the API and pass it to a separate component that will render the chart. Let us replace the contents of App.js with the code below:



import { useEffect, useState } from "react";

export default function App() {
  const [data, setdata] = useState();

  useEffect(() => {
    const fetchDatas = async () => {
      const res = await fetch("https://api.coincap.io/v2/assets/?limit=20");
      const data = await res.json();
      console.log(data);
      setdata(data?.data);
    };
    fetchDatas();
  }, []);

  return <div className="App">How to use Recharts with React</div>;
}


Enter fullscreen mode Exit fullscreen mode

I've written a function called fetchData that queries the CoinCap API.

The API returns a data property with 100 cryptocurrency objects by default. To request only the first twenty objects stored in our data state, I added a limit parameter at the end of the URL.

In addition, fetchData was called in a useEffect hook with an empty dependency array, indicating that the function is executed as soon as the App component is mounted.

The next step is to start our application with:

npm start

We should have something that looks like the image below.

first draft

Let's see what the data we fetched looks like in the console:

We should have something that looks like the image below.

seconddraft

In order to create our chart, we will only need the name and priceUsd properties from the data.

Chart Component

In the src directory, we create a Chart.js file and add the code below:



import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";

export default function Chart({ data }) {
  return (
    <ResponsiveContainer width="100%" height={400}>
      <BarChart
        data={data}
        margin={{
          top: 5,
          right: 30,
          left: 20,
          bottom: 5,
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Bar dataKey="name" fill="#8884d8" />
        <Bar dataKey="priceUsd" fill="#82ca9d" />
      </BarChart>
    </ResponsiveContainer>
  );
}


Enter fullscreen mode Exit fullscreen mode

In our Chart.js file, we import the following components from Recharts BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer to represent the data. Also, we passed our data as a prop.

Next, we add our Chart.js component to our app.js file and pass our data
state into Chart.js as a prop.




import { useEffect, useState } from "react";
import Chart from "./Chart";

export default function App() {
  const [data, setdata] = useState();

  useEffect(() => {
    const fetchDatas = async () => {
      const res = await fetch("https://api.coincap.io/v2/assets/?limit=20");
      const data = await res.json();
      console.log(data);
      setdata(data?.data);
    };
    fetchDatas();
  }, []);

  return (
    <div className="App">
      How to use Recharts with React
      <Chart data={data} />
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

To run our final code, we can follow the steps below:

npm start

We should have something that looks like the image below.

Draftthree

Conclusion

This article shows how to display charts on websites using Recharts and React, but it goes much further.

For more information about Recharts and more ways to customize your charts, visit the Recharts website.


Thanks for Reading 🌟🎉


It's great to see that you have enjoyed the article. Please, let me know what you think in the comment section.

I'd love to connect with you at Twitter


On to another blog, some other day, till then Femi👋.

Top comments (2)

Collapse
 
abid365 profile image
Syed Jawad Bin Azam

I did the exact thing but my chart is not showing in the ui and the data props is not passing data to the component

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

did you follow everything in the article ?