The React wrapper for chart.js is react-chartjs-2, which simplifies things in React. However, it doesn’t support all the customization features of Chart.js.
Here are the steps to create charts in React.
Step 1: Install React Project
npx create-react-app reactjscharttutorial
Move to the project folder by cd command and start the development server by typing the following code.
yarn start
Step 2: Add Chart.js Library
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 a Chart
Go to the src >> components folder and create a new file called BarChartComponent.js.
// 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 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> ) } }
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 the create_charts_table.php file 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.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); } }
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.
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, 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.
That’s it.
Chimereze Ikenna-Alfred
Awesome you just saved me some headache