banner



How To Create Pie Chart In React Js

We will use the Axios libraryto send an AJAX request to the Laravel API. Axios is a promise-based javascript library.

How to Create Charts in React

In this tutorial, we will use the Chart.js library to display the charts.We will discuss two charts in this tutorial. First is the BarChart, which uses bars to show comparisons between categories of data. The second is the PieChart, generally used to indicate percentage or proportional data. We will use Laravel as a backend to serve the data.

First, we install the React.js skeleton project.

Step 1: Install React Project

Open your terminal and type the following command.

npx create-react-app reactjscharttutorial

Move to the project folder bycdcommand and start the development server by type the following code.

yarn start

Step 2: Add Chart.js Library

Now, we can add the chartjs library to react js by typing the following command.

yarn add react-chartjs-2 chart.js

Step 3: Define a React Component to create Chart

Go to thesrc  >> components folder and create a new file called BarChartComponent.js.

This file is created for the BarChart.

//BarChartComponent.js import React, { Component } from 'react'; import {Bar} from 'react-chartjs-2';   export default class BarChartComponent extends Component {    constructor(props) {       super(props);       this.state ={        }   }    render()    {       return(          <div>             <Bar/>          </div>       )    } }

Go to thesrc  >> components folder and create a new file called PieChartComponent.js. This file is created for PieChart.

//PieChartComponent.js import React, { Component } from 'react'; import {Pie} from 'react-chartjs-2';   export default class PieChartComponent extends Component {    constructor(props) {       super(props);       this.state ={        }   }    render()    {       return(          <div>             <Pie/>          </div>       )    } }

Next, we can add components in the App.js file.

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import BarChartComponent from './components/BarChartComponent'; import PieChartComponent from './components/PieChartComponent';  class App extends Component {   render() {     return (       <div className="App">       <h1>BarChart</h1>         <BarChartComponent/>       <h1>PieChart</h1>         <PieChartComponent/>       </div>     );   } }  export default App;        

Step 4: Install Laravel

Install Laravel by typing the following command.

composer create-project --prefer-dist laravel/laravel LaravelReactJSChart

Step 5: Configure the database.

Add the database credentials in the .env file

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravelreactchart DB_USERNAME=root DB_PASSWORD=

Step 6: Create a model and migration files.

php artisan make:model Chart -m        

It will create a model and migration file.

Step 7: Define the schema in the migration file.

Go to thecreate_charts_table.phpfile and add the schema to it.

public function up()     {         Schema::create('charts', function (Blueprint $table) {             $table->increments('id');             $table->string('name');             $table->integer('score');             $table->timestamps();         });     }

Step 8: Define the routes in the api.php file.

We can create a controller called ChartController.php.

php artisan make:controller ChartController --resource

Add the following route in the api.phpfile.

Route::get('charts', 'ChartController@index');

Code theindex functioninside that file.

//Chartontroller.php  <?php  namespace App\Http\Controllers; use App\Chart;  use Illuminate\Http\Request;  class ChartController extends Controller {     /**      * Display a listing of the resource.      *      * @return \Illuminate\Http\Response      */     public function index()     {         $charts = Chart::all();         return response()->json($charts);     } }

The above code retrieves all the data as a collection and then returns an array of charts as a JSON response.

Right now, we do not have any players in the database. So for this example, we need to fill it manually because we are not writing any screen that can store the details of the player name.

Laravel API Tutorial

Now, start the Laravel development server with the following command.

php artisan serve

Step 9: Add axios to a component file .

 You require axios. Switch to your terminal and type the following command to add axios.

yarn add axios          

Now, we can send the request using Axios. After processing the request, it sends the response; we create two variables like playername and playerscore. In playername, we can put the name we can get from the response, and In playerscore, we can put a score that can get the response.

So we have created two arrays that handle both playername and playerscore. Assign both the variables to the BarChartComponent, and we can see the Barchart.

//BarChartComponent.js  import React, { Component } from 'react'; import {Bar} from 'react-chartjs-2'; import axios from 'axios';  export default class BarChartComponent extends Component {    constructor(props) {       super(props);       this.state = {         Data: {}       }     }               componentDidMount() {         axios.get(`http://localhost:8000/api/charts`)           .then(res => {             const football = res.data;             let playername = [];             let playerscore = [];             football.forEach(element => {               playername.push(element.name);               playerscore.push(element.score);             });             this.setState({                Data: {                 labels: playername,                 datasets:[                    {                       label:'Champions League 2017/2018 Top Scorer',                       data: playerscore ,                       backgroundColor:[                        'rgba(255,105,145,0.6)',                        'rgba(155,100,210,0.6)',                        'rgba(90,178,255,0.6)',                        'rgba(240,134,67,0.6)',                        'rgba(120,120,120,0.6)',                        'rgba(250,55,197,0.6)'                     ]                    }                 ]              }              });           })       }  render()    {       return(         <div>           <Bar             data = {this.state.Data}             options = {{ maintainAspectRatio: false }} />         </div>       )    } }

In Piechart, we use the same method, and we need to import the Pie component, and the rest is the same.

//PieChartComponent.js  import React, { Component } from 'react'; import {Pie} from 'react-chartjs-2'; import axios from 'axios';  export default class PieChartComponent extends Component {    constructor(props) {       super(props);       this.state = {         Data: {}       }     }             componentDidMount() {       axios.get(`http://localhost:8000/api/charts`)         .then(res => {           const football = res.data;           let playername = [];           let playerscore = [];           football.forEach(element => {             playername.push(element.name);             playerscore.push(element.score);           });           this.setState({              Data: {               labels: playername,               datasets:[                  {                     label:'Champions League 2017/2018 Top Scorer',                     data: playerscore ,                     backgroundColor:[                      'rgba(255,105,145,0.6)',                      'rgba(155,100,210,0.6)',                      'rgba(90,178,255,0.6)',                      'rgba(240,134,67,0.6)',                      'rgba(120,120,120,0.6)',                      'rgba(250,55,197,0.6)'                   ]                  }               ]            }            });         })     }  render()    {       return(         <div>         <Pie           data={this.state.Data}           options={{maintainAspectRatio: false}}/>      </div>       )    } }

In the above tutorial, you may face the No 'Access-Control-Allow-Origin' header on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. You will get rid of this error by going to the Laravel React Example.  The best possible solution is there.

React js Charts Tutorial

That's it for this tutorial.

How To Create Pie Chart In React Js

Source: https://appdividend.com/2018/03/26/how-to-create-charts-in-react-js/

Posted by: ruddmyris1978.blogspot.com

0 Response to "How To Create Pie Chart In React Js"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel