How to Create a Line Chart in React

This article will teach us how to create a Line chart in  React application.

Prerequisites of React

  • Familiarity with the HTML, JavaScript.
  • node.js installed

Create React Project

To create a React app, use the following command in the terminal

npx create-react-app matui

Install Bootstrap

Now install Bootstrap by using the following command.

npm install bootstrap

Now, open the index.js file and add the import Bootstrap. 

import 'bootstrap/dist/css/bootstrap.min.css';

Install Google Charts 

Now install Google chart by using the following command.

npm install react-google-charts

Now right-click on the src folder and create a new component named 'Linechart.js'

import React, { Component } from 'react'
import Chart from 'react-google-charts'
const LineData = [
    ['x', 'Csk', 'GT','MI'],
    [0, 0, 0,0],
    [1, 10, 5,12],
    [2, 23, 15,17],
    [3, 17, 9,18],
    [4, 18, 10,10],
    [5, 9, 5,11],
    [6, 11, 3,13],
    [7, 27, 19,21],
]
const LineChartOptions = {
    hAxis: {
        title: 'Time',
    },
    vAxis: {
        title: 'Popularity',
    },
    series: {
        1: { curveType: 'function' },
    },
}
export default class Linechart extends Component {
    render() {
        return (
            <div className="container mt-5">
                <h2>How to Create Line Chart in React Application</h2>
                <Chart
                    width={'700px'}
                    height={'410px'}
                    chartType="LineChart"
                    loader={<div>Loading Chart</div>}
                    data={LineData}
                    options={LineChartOptions}
                    rootProps={{ 'data-testid': '2' }}
                />
            </div>
        )
    }
}

In the above code, we have added a Multiline chart to show data comparison for three objects.

Now, import the Linechart component in the src/App.js file.

import logo from './logo.svg';
import './App.css';
import Linechart from './Linechart'
function App() {
  return (
    <div className="App">
      <Linechart/>
    </div>
  );
}

export default App;

Now, run the project using the 'npm start' command and check the result.

Line Chart in React Application

Summary

This article provides a step-by-step guide on creating a line chart in a React application using the Google Charts library.