How to Create a Chart in React With Recharts
Tags: react, tutorial, beginners, javascript
Published: 2022-09-01 10:42:03

## 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](https://recharts.org/en-US/) 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](https://reactjs.org/).

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](https://docs.coincap.io/), we'll be able to get real-time cryptocurrency prices for our React application.

## Prerequisites

<p>To follow along, you’ll need the following:</p>
<ul>
<li>
<a href="https://nodejs.org/en/"  target="_blank" rel="noreferrer"  >
Node.js </a> version 16.16.0 installed on your computer.

</li>

<li>
A new React project set up with
<a href="https://reactjs.org/docs/create-a-new-react-app.html" >Create React App</a>
</li>

<li>IDE or text editor of your choice, such as <a href="https://www.sublimetext.com/" target="_blank" rel="noreferrer noopener"  >Sublime Text</a> or <a href="https://code.visualstudio.com/" target="_blank" rel="noreferrer noopener">Visual Studio Code</a></li>

</ul>

<h2 id="Setting up our React project">Setting up our React project</h2>

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

<pre>
npx create-react-app react-recharts-tutorial
</pre>

<p>We will now navigate to the project directory by running:</p>

<pre>
cd react-recharts-tutorial
</pre>

<p>

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

</p>

<p>
Currently, this is how my project structure looks.
</p>

![Folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rud26ax8vu95tfchtyby.png)

<h2 id="Adding Recharts to our React app"  >Installing Recharts into our React application</h2>

To install Recharts, we run the following command:

<pre>
npm install recharts
</pre>


<p>

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

</p>

<p>
 This is the current state of my dependencies.

</p>


```javascript

//...

  "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"
  },

  //...


```

<h2>React code cleanup</h2>

The <code>create react app</code> 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 <code>App.css</code>  or <code>logo.svg</code> inside the <code>src</code> folder. We can delete all the code in <code>App.js</code>.





<h2>Fetching the data</h2>


<p>
In <code>App.js</code>, 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 <code>App.js</code> with the code below:

</p>

```javascript
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>;
}
```

<p>

I've written a function called <code>fetchData</code> that queries the CoinCap API. </p>

<p>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 <code>limit</code> parameter at the end of the URL.</p>



In addition, <code>fetchData</code> was called in a [useEffect hook](https://reactjs.org/docs/hooks-effect.html) with an empty dependency array, indicating that the function is executed as soon as the App component is mounted.

<p>The next step is to start our application with:</p>



<pre>npm start</pre>

<p>We should have something that looks like the image below.</p>

![first draft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hsj5skzlh0dnq1k5hhoj.png)

<p>
Let's see what the data we fetched looks like in the console:</p>

<p>We should have something that looks like the image below.</p>

![seconddraft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jt9ap8yj2sdevz5dwqj.png)

<p>In order to create our chart, we will only need the <code>name</code> and <code>priceUsd</code>  properties from the data.</p>


<h2>Chart Component</h2>

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

```javascript
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>
  );
}
```



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




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



```javascript

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>
  );
}
```


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

<pre>npm start</pre>

<p>We should have something that looks like the image below.</p>



![Draftthree](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p40dnja6ldxd16jr0a1e.png)

## Conclusion

<span>

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](https://recharts.org/en-US/)  website.

</span>

<span>
Thanks for Reading 🌟🎉
</span>

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

</span>

<span>I'd love to connect with you at <a href="https://twitter.com/akinyemi_t">Twitter</a> </span>

</span>
On to another blog, some other day, till then Femi👋.
</span>