Precious Luke Open source crusader. I love building stuff with great technology.

Using Recharts in React to add charts

5 min read 1496

Visualization is essential these days and how you present information matters. With an excess of data at our fingertips, this data can often be tedious to sort through and understand, especially when not presented well.

To make data more digestible, charts are a great way to organize and visualize data. For React apps, developers can use Recharts, an open source “composable charting library built on React components” based in JavaScript.

In this tutorial, we’ll learn how to use Recharts by building a small React application that fetches data from a Sanity content lake to summarize an extensive dataset in a visually appealing way.

Recharts tutorial requirements

To follow along with this tutorial, you must have the following:

  • Node.js v14 installed on your computer
  • A code editor (I am using Visual Studio Code)
  • Yarn package manager

Setting up the Recharts project

To begin our project, we must first install Sanity CLI on our machine, which can be done by running the following command:

yarn install -g @sanity/cli

This installs the command-line tool globally to set up new projects, manage datasets, import data, and more. We will use it to get our project up and running.

For much more information on this, read the Sanity documentation.

Creating a Sanity project

Next, we must start our Sanity project. To do that, run the following command:

sanity init

The above command will ask you to select your login type: either Google, GitHub, Email/password.

Selecting Login Type

You can select the most convenient one for your project, which will immediately open your default browser and complete the sign-up/login process.

Login Successful Screen

Going back to your terminal, you will be prompted to:

  • Import your preferred project name
  • Choose a dataset preference (use the default)
  • Confirm the path to the project
  • Choose a schema

As of posting this article, Sanity only provides three out-of-the-box, already populated schemas: Movie project (schema + sample data), E-commerce (Schema + sample data), and Blog(schema + empty data).

However, for this project, we must choose the Clean project with no predefined schemas option because we must define our schema by ourselves.

Defining Schemas in VS Code

After the installation completes, we can see the files and folders created within our project folder. To start Sanity, run the following command:

sanity start

Starting Sanity in VS Code

Next, we must install the necessary node modules, compile, and start the project at http://localhost:3333. While logging in, make sure you select the same provider you used when creating the project.

Logging In To Install Modules For Sanity

Now, let’s add our schema code; this is simply content modeling, the process of identifying, collating, and relating all of the contents into a centralized structure so we can build efficient workflows and data structures.

Adding Schema Code To Empty Schema In Sanity

 

You can find more information about content modeling in Sanity here.

The data we will use in this project comes from the John Hopkins GitHub page, which provides a daily report of Covid cases, including the fields we are interested in: province/state, confirmed cases, and the number of deaths.

We’ll specifically use the 01/01/2021 data to be represented in our chart. To do this, first, create a file within the schemas folder called covid.js, and copy and paste the code below.

This file defines the structure of the particular schema:

// schemas/covid.js

export default{
    name: "covid",
    type : "document",
    title: "Covid19Data",
    fields: [
      {
      name: "title",
      type: "string",
      title: "States"
      },
      {
        name: "confirmed",
        type: "number",
        title: "Confirmed"
      },
        {
          name: "death",
          type: "number",
          title: "Death"
          },
    ],
  }

Now, we must import the covid.js into our schema.js file within our schemas folder, like so:

// schemas/schema.js
// First, we must import the schema creator
import createSchema from 'part:@sanity/base/schema-creator'
// Then import schema types from any plugins that might expose them
import schemaTypes from 'all:part:@sanity/base/schema-type'
import covid from './covid'
// Then we give our schema to the builder and provide the result to Sanity
export default createSchema({
  // We name our schema
  name: 'default',
  // Then proceed to concatenate our document type
  // to the ones provided by any plugins that are installed
  types: schemaTypes.concat([
    /* Your types here! */
    covid,

  ]),
}

Now, going back to http://localhost:3333, we will see this:

Covid19 Document Created In The Sanity Schema

Covid19Data is the title of the document we created in the schema that has States, Confirmed, and Death within it.

States showcases the places of the Covid cases, Confirmed shows the number of people who tested positive for Covid, and Death shows the number of people who died from Covid in that particular state.



We can now populate our project with data from the 01/01/2021 dataset.

Populating Project With Covid Data

Note that we must only copy Province_State, Confirmed, and Deaths columns from the following:

Copying Covid19 Data

Creating a React application

Now that our Sanity project is up and running, it is time to set up our frontend application with React.

First, create an empty folder and run this command:

npx create-react-app frontendfinal

frontendfinal is the name I decided to call my project, but remember, yours can be anything.

After installing React, it is time to install Recharts. First, cd into frontendfinal

cd frontendfinal

Then, we can install recharts:

npm install recharts

Open it up in your text editor and navigate to package.json, which opens the following:

Opening Package.json In VS Code

Now, Recharts is installed in our React app!

Cleaning up the React code

The create react app command bootstraps a React application quickly; now, we just need to make some modifications for it to fit our use case because we don’t need everything create react app comes with.

For this particular use case, we do not need to use App.css or logo.svg inside the src folder; simply delete all the code inside App.js.

Installing a Sanity client

For your React application to connect to your Sanity instance running, you must install sanity/client by running this command:

npm install --save @sanity/client

Next, create a file inside the src folder. I decided to use clientDetail.js, so inside clientDetail.js, copy and paste the following code and replace details appropriately:

// src/clientDetails.js
const sanityClient = require('@sanity/client')
const client = sanityClient({
  projectId: 'xxxxxxx',
  dataset: 'production',
  apiVersion: '2021-03-25', // use a UTC date string
  useCdn: false, // `false` if you want to ensure fresh data
})
export default client;

You can get your projectId by logging into your Sanity account and selecting your project. Other information like datasets is there as well.

Getting The Project ID From Sanity

Again, to avoid CORS issues, Sanity lets you add the origin where your request will come from. To add a new origin, follow the steps below:

  • Under Settings > API settings > CORS origins
  • Click ADD CORS origin and add http://localhost:3000, which is your React URL
  • When deploying this application, add your application URL
  • Check Allow Credential > Save

The steps have been numbered visually in the screenshot below:

Adding Request Origin In Sanity To Avoid CORS Issues

Back in our App.js file, we must import the following: useState, useEffect from react, client from clientDetails.js file, and import some components from Recharts (LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, and Legend) to represent the data.

Our App.js file will look like so:

// src/App.js
import React, { useState, useEffect } from "react";
import client from "./clientDetails";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from "recharts";

Then, we can create a functional component named App that will use useState, useEffect, and fetch data from our Sanity instance using GROQ:

// src/App.js
import React, { useState, useEffect } from "react";
import client from "./clientDetails";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from "recharts";
export default function App() {
  const [covidData, setcovidData] = useState(null);
  useEffect(() => {
    client
      .fetch(
        `*[_type == 'covid']{
      confirmed,
      title,
      death
      }`
      )
      .then((data) => {
        setcovidData(data);
      })
      .catch(console.error);
  }, []);

We must then return a div tag containing all the imported Recharts components and some defined properties.

Our App.js full code should be as follows:

// src/App.js
import React, { useState, useEffect } from "react";
import client from "./clientDetails";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from "recharts";
export default function App() {
  const [covidData, setcovidData] = useState(null);
  useEffect(() => {
    client
      .fetch(
        `*[_type == 'covid']{
      confirmed,
      title,
      death
      }`
      )
      .then((data) => {
        setcovidData(data);
      })
      .catch(console.error);
  }, []);
  return (
    <div>
      {!covidData && <div>Loading</div>}
      {covidData && (
        <LineChart
          width={1000}
          height={400}
          data={covidData}
          margin={{
            top: 10,
            right: 30,
            left: 0,
            bottom: 0,
          }}
        >

          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="title" />
          <YAxis />
          <Tooltip />
          <Legend />
          <Line
            type="monotone"
            dataKey="death"
            stroke="#8884d8"
            fill="#8884d8"
          />
           <Line
            type="monotone"
            dataKey="confirmed"
            stroke="#8884d8"
            fill="#8884d8"
          />
        </LineChart>
      )}
    </div>
  );
}

To run our finalized code, we can run our React application with the following:

npm run start

Then, we can start it up at http://localhost:3000/:

Final Recharts Graph Showing States And Corresponding Covid Data

Congratulations, you were able to see this through!

Conclusion

Visualization is essential to organize data, and it is paramount that we present it intelligently and concisely. We were able to fetch data from Sanity to our React application and display it using Recharts.

You can find the source code for this project for the React app and the Sanity codebase here.

Cut through the noise of traditional React error reporting with LogRocket

LogRocket is a React analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your React applications. LogRocket automatically aggregates client side errors, React error boundaries, Redux state, slow component load times, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to notify you of the most impactful problems affecting the most users and provides the context you need to fix it.

Focus on the React bugs that matter — .

Precious Luke Open source crusader. I love building stuff with great technology.

Leave a Reply