How to Create Charts in Reactjs is the topic, we will cover today. In this tutorial, we will use Chart.js library to display the charts. We will discuss two charts in this tutorial. First is the BarChart, uses bars to show comparisons between categories of data. Second is the PieChart, generally used to indicate percentage or proportional data. We will use Laravel as a backend to serve the data. I will use Axios library to send an AJAX request to the Laravel API. Axios is a promise based javascript library.
How to Create Charts in Reactjs
First, we install the React.js skeleton project.
Step 1: Install React js Project
Open your terminal and type following command.
npx create-react-app reactjscharttutorial
Move to the project folder by cd command and start the development server by type the following code.
yarn start
Step 2: Add Chartjs Library
Now, we can add the chartjs library in react js by typing following command.
yarn add react-chartjs-2 chart.js
Step 3: Define a React Component to create Chart
Go to the src >> 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 the src >> components folder and create a new file called PieChartComponent.js.This file is created for the 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 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 5.6
Install Laravel by typing following command.
composer create-project --prefer-dist laravel/laravel LaravelReactJSChart
Step 5: Configure the database.
Add 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 model and migration files.
php artisan make:model Chart -m
It will create model and migration file.
Step 7: Define the schema in the migration file.
Go to the create_charts_table.php file and add the schema into 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 following route in the api.php file.
Route::get('charts', 'ChartController@index');
Code the index function inside 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);
}
}
Above code retrieves all the data as a collection and then return an array of charts as a JSON response
Right now, we do not have any player 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.
Now, start the Laravel development server by the following command.
php artisan serve
Step 9: Add axios to a component file.
You require axios.Turn to your terminal and type 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 variable like playername and playerscore. In playername, we can put name which we can get from the response, and In playerscore, we can put score which 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 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 above tutorial, you may face No ‘Access-Control-Allow-Origin’ header is present 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 5.5 ReactJS Tutorial The best possible solution is there.
So finally, our How to Create Charts in Reactjs is over
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.