In this tutorial, we will learn how to use Google Charts to draw a trend line chart in a React App.
Firstly, we should know that a trend line is a line superimposed on a chart unveiling the overall direction of the data. For creating the trend line chart, we will add the React Google Charts package in React.
This package also offers other charts like Scatter Charts, Bar Charts, Column Charts, Line Charts, etc.
React Js Google Trend Lines Chart Example
Step 1- Create React App
Step 2- Install React Google Charts Package
Step 3- Build Trend Lines Component
Step 4- Add Chart Component In App Js
Step 5- Run The Application
Let’s learn in detail:
Step 1- Create React App
The basic step is to create a new react project for which we will have to use the following command:
npx create-react-app demo-app
Since the app, is generated, we will enter into it:
cd demo-app
Then, we have to install the bootstrap package:
npm install bootstrap
Afterward, we will import the bootstrap into the App.js file:
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
Step 2- Install React Google Charts Package
In the second step, we need to use the given command to install the Google Charts library in the React app:
# npm
npm install react-google-charts
# yarn
yarn add react-google-charts
Step 3- Build Trend Lines Component
Here, we will create the ‘components’ directory after which we create a new TrendChart.js file into the folder.
For building the trend chart, we have to add the given code into the components/TrendChart.js:
import React, { Component } from 'react'
import Chart from 'react-google-charts'
const TrendData = [
['Diameter', 'Age'],
[8, 37],
[4, 19.5],
[11, 52],
[4, 22],
[3, 16.5],
[6.5, 32.8],
[14, 72],
]
const TrendOptions = {
title: 'Age of sugar maples vs. trunk diameter, in inches',
hAxis: { title: 'Diameter' },
vAxis: { title: 'Age' },
legend: 'none',
trendlines: { 0: {} },
}
class TrendChart extends Component {
render() {
return (
<div>
<h2>React Trend Line Chart Example</h2>
<Chart
width={'600px'}
height={'350px'}
chartType="ScatterChart"
loader={<div>Loading Chart</div>}
data={TrendData}
options={TrendOptions}
rootProps={{ 'data-testid': '1' }}
/>
</div>
)
}
}
export default TrendChart
Step 4- Add Chart Component In App Js
Now, the chart is ready. We have to import the chart component in the App.js file:
import React from 'react'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import TrendChart from './components/TrendChart'
function App() {
return (
<div className="container mt-3">
<TrendChart />
</div>
)
}
export default App
Step 5- Run The Application
So now, the trend diagram is ready and we will run the app by using the given command:
npm start
Conclusion
So friend, throughout this guide, we have learned how to create a simple line chart. Also, we can create a polynomial and exponential trend line chart.
Thanks