In this article, we will learn how to create charts in ReactJS application using the Chart.js library. Chart.js is an open source JavaScript library for creating charts. Chart.js makes it easier to draw different types of charts like line chart, bar chart, doughnut chart, area chart etc. In this article, we will create a line chart, bar chart, pie chart, and polar area using ReactJS and Web API Learn more about
chart.js.
Prerequisites
- Basic knowledge of ReactJS and Web API.
- Visual Studio and Visual Studio Code can be installed
- SQL Server Management Studio
This article covers,
- Create a database and table.
- Create a Asp.net Web API Project.
- Create ReactJS Project.
- Install Chart.js Library
- Install Bootstrap and axios
- Add Routes in ReactJS
Step 1 - Create a Table in the Database
Open SQL Server Management Studio, create a database named "DemoTest" and in this database, create a table. Give that table a name like "Ipltopscorer."
- CREATE TABLE [dbo].[Ipltopscorer](
- [id] [int] IDENTITY(1,1) NOT NULL,
- [Playername] [varchar](50) NULL,
- [Runscore] [int] NULL,
- CONSTRAINT [PK_Ipltopscorer] PRIMARY KEY CLUSTERED
- (
- [id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
Add some demo data into this table.
Step 2 - Create a New Asp.net Web API Project
Open Visual Studio and create a new project
Change the name as ChartDemo and click on Ok
Select Web API as its template.
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
Click on the "ADO.NET Entity Data Model" option and click "Add".
Select EF Designer from the database and click the "Next" button
Add the connection properties and select database name on the next page and click OK.
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button
Our data model is successfully created now.
Right-click on the Controllers folder and add a new controller. Name it as "Chartcontroller".
Add the following namespace in the Charts Controller.
Add a new method to fetch data from the database.
- public object Getrecord()
- {
- DemoTestEntities DB = new DemoTestEntities();
- return Json(DB.Ipltopscorers.ToList());
- }
Complete the Chartcontroller code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using ChartDemo.Models;
-
- namespace ChartDemo.Controllers
- {
- [RoutePrefix("API/Charts")]
- public class ChartController : ApiController
- {
- [Route("Getrecord")]
- [HttpGet]
- public object Getrecord()
- {
- DemoTestEntities DB = new DemoTestEntities();
- return Json(DB.Ipltopscorers.ToList());
- }
- }
- }
Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors and install the "Microsoft.Asp.Net.WebApi.Cors" package.
- EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
Create ReactJS Project
Now create a new React.js project by using the following command.
- npx create-react-app reactcharts
Open the newly created project in Visual Studio code.
Install Chartjs Library
Now, install chartjs library in react project by typing the following command.
- npm install react-chartjs-2 chart.js
Install bootstrap in this project by using the following command.
- npm install --save bootstrap
Now, open the index.js file and import Bootstrap.
- import 'bootstrap/dist/css/bootstrap.min.css';
Now Install the Axios library by using the following command. Learn more about
Axios
Now go to src folder and add 5 new components.
- Linechart.js
- Barchart.js
- Doughnut.js
- Piechart.js
- Polararea.js
Now open Linechart.js and import Line chart from chart.js library and add following code
- import React, { Component } from 'react'
- import axios from 'axios';
- import { Line } from 'react-chartjs-2';
- export class Linecharts extends Component {
- constructor(props) {
- super(props);
- this.state = { Data: {} };
- }
- componentDidMount() {
- axios.get(`http:
- .then(res => {
- console.log(res);
- const ipl = res.data;
- let playername = [];
- let runscore = [];
- ipl.forEach(record => {
- playername.push(record.Playername);
- runscore.push(record.Runscore);
- });
- this.setState({
- Data: {
- labels: playername,
- datasets: [
- {
- label: 'IPL 2018/2019 Top Run Scorer',
- data: runscore,
- backgroundColor: [
- "#3cb371",
- "#0000FF",
- "#9966FF",
- "#4C4CFF",
- "#00FFFF",
- "#f990a7",
- "#aad2ed",
- "#FF00FF",
- "Blue",
- "Red"
- ]
- }
- ]
- }
- });
- })
- }
- render() {
- return (
- <div>
- <Line
- data={this.state.Data}
- options={{ maintainAspectRatio: false }} />
- </div>
- )
- }
- }
-
- export default Linecharts
Now open Barchart.js and add following code,
- import React, { Component } from 'react'
- import axios from 'axios';
- import { Bar } from 'react-chartjs-2';
- export class Barchart extends Component {
- constructor(props) {
- super(props);
- this.state = { Data: {} };
- }
- componentDidMount() {
- axios.get(`http:
- .then(res => {
- console.log(res);
- const ipl = res.data;
- let playername = [];
- let runscore = [];
- ipl.forEach(record => {
- playername.push(record.Playername);
- runscore.push(record.Runscore);
- });
- this.setState({
- Data: {
- labels: playername,
- datasets: [
- {
- label: 'IPL 2018/2019 Top Run Scorer',
- data: runscore,
- backgroundColor: [
- "#3cb371",
- "#0000FF",
- "#9966FF",
- "#4C4CFF",
- "#00FFFF",
- "#f990a7",
- "#aad2ed",
- "#FF00FF",
- "Blue",
- "Red"
- ]
- }
- ]
- }
- });
- })
- }
- render() {
- return (
- <div>
- <Bar data={this.state.Data}
- options={{ maintainAspectRatio: false }} />
- </div>
- )
- }
- }
-
- export default Barchart
Now open Doughnut.js and add the following code,
- import React, { Component } from 'react'
- import axios from 'axios';
- import {Doughnut} from 'react-chartjs-2';
- export class Doughnutchart extends Component {
- render() {
- return (
- <div>
-
- </div>
- )
- } constructor(props) {
- super(props);
- this.state = { Data: {} };
- }
- componentDidMount() {
- axios.get(`http:
- .then(res => {
- console.log(res);
- const ipl = res.data;
- let playername = [];
- let runscore = [];
- ipl.forEach(record => {
- playername.push(record.Playername);
- runscore.push(record.Runscore);
- });
- this.setState({
- Data: {
- labels: playername,
- datasets: [
- {
- label: 'IPL 2018/2019 Top Run Scorer',
- data: runscore,
- backgroundColor: [
- "#3cb371",
- "#0000FF",
- "#9966FF",
- "#4C4CFF",
- "#00FFFF",
- "#f990a7",
- "#aad2ed",
- "#FF00FF",
- "Blue",
- "Red"
- ]
- }
- ]
- }
- });
- })
- }
- render() {
- return (
- <div>
- <Doughnut data={this.state.Data}
- options={{ maintainAspectRatio: false }} />
- </div>
- )
- }
- }
-
- export default Doughnutchart
Now open Piechart.js and add the following code,
- import React, { Component } from 'react'
- import axios from 'axios';
- import { Pie } from 'react-chartjs-2';
- export class Piechart extends Component {
- constructor(props) {
- super(props);
- this.state = { Data: {} };
- }
- componentDidMount() {
- axios.get(`http:
- .then(res => {
- console.log(res);
- const ipl = res.data;
- let playername = [];
- let runscore = [];
- ipl.forEach(record => {
- playername.push(record.Playername);
- runscore.push(record.Runscore);
- });
- this.setState({
- Data: {
- labels: playername,
- datasets: [
- {
- label: 'IPL 2018/2019 Top Run Scorer',
- data: runscore,
- backgroundColor: [
- "#3cb371",
- "#0000FF",
- "#9966FF",
- "#4C4CFF",
- "#00FFFF",
- "#f990a7",
- "#aad2ed",
- "#FF00FF",
- "Blue",
- "Red"
- ]
- }
- ]
- }
- });
- })
- }
- render() {
- return (
- <div>
- <Pie
- data={this.state.Data}
- options={{ maintainAspectRatio: false }} />
- </div>
- )
- }
- }
-
- export default Piechart
Now open Polararea.js and add the following code,
- import React, { Component } from 'react'
- import { Polar } from 'react-chartjs-2';
- import axios from 'axios';
-
- export class Polararea extends Component {
- constructor(props) {
- super(props);
- this.state = { Data: {} };
- }
- componentDidMount() {
- axios.get(`http:
- .then(res => {
- console.log(res);
- const ipl = res.data;
- let playername = [];
- let runscore = [];
- ipl.forEach(record => {
- playername.push(record.Playername);
- runscore.push(record.Runscore);
- });
- this.setState({
- Data: {
- labels: playername,
- datasets: [
- {
- label: 'IPL 2018/2019 Top Run Scorer',
- data: runscore,
- backgroundColor: [
- "#3cb371",
- "#0000FF",
- "#9966FF",
- "#4C4CFF",
- "#00FFFF",
- "#f990a7",
- "#aad2ed",
- "#FF00FF",
- "Blue",
- "Red"
- ]
- }
- ]
- }
- });
- })
- }
- render() {
- return (
- <div>
- <Polar data={this.state.Data}
- options={{ maintainAspectRatio: false }} />
- </div>
- )
- }
- }
-
- export default Polararea
Add Routing in ReactJS
Install react-router-dom package by using the following command
- npm install react-router-dom --save
Now open app.js file and import all 5 components and React router component. Add the following code in app.js file
- import React from 'react';
- import './App.css';
- import Piechart from './piechart'
- import Doughnutchart from './Doughnutchart'
- import Barchart from './Barchart'
- import Linecharts from './linecharts'
- import Polararea from './Polararea'
- import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
- function App() {
- return (
- <div className="App">
- <Router>
- <div>
- <div class="row" className="hdr">
- <div class="col-sm-12 btn btn-warning">
- Charts in ReactJS
- </div>
- </div>
- <div class="row" style={{ marginTop: "10px" }}> >
- <div class="col-sm-1">
- </div>
- <div class="col-sm-2">
- <Link to={'/Piechart'} className="nav-link btn btn-info">Piechart</Link>
- </div>
- <div class="col-sm-2">
- <Link to={'/Barchart'} className="nav-link btn btn-info">Bar Chart</Link>
- </div>
- <div class="col-sm-2">
- <Link to={'/Linecharts'} className="nav-link btn btn-info">Line Chart</Link>
- </div>
- <div class="col-sm-2">
- <Link to={'/Doughnut'} className="nav-link btn btn-info">Doughnut Chart</Link>
- </div>
- <div class="col-sm-2">
- <Link to={'/Polararea'} className="nav-link btn btn-info">Polar Chart</Link>
- </div>
- <div class="col-sm-1">
- </div>
- </div>
- </div>
- <div className="container">
- <Switch>
- <Route exact path='/Piechart' component={Piechart} />
- <Route path='/Barchart' component={Barchart} />
- <Route path='/Polararea' component={Polararea} />
- <Route path='/Doughnut' component={Doughnutchart} />
- <Route path='/Linecharts' component={Linecharts} />
- </Switch>
- </div>
- </Router>
- </div>
- );
- }
- export default App;
Now run the project by using ‘npm start’ command and check the result. Click on the buttons to check all charts.
Summary
In this article, we learned about Chart.js and how we add chart.js in ReactJS applications to create Charts. In this article, we discussed the line chart, bar chart, pie chart, doughnut chart, and polar area chart. We can also use other Chart libraries in reactjs for creating charts and graphs.