Categories
PHP React

React Recharts Chart Example with PHP Backend

First of all we need to create our database. I am choosing SQLite as always. We got 4 columns: id, temperature, humidity and day.

chart.db

CREATE TABLE "dataset" (
	"id"	INTEGER PRIMARY KEY AUTOINCREMENT,
	"temperature"	INTEGER,
	"humidity"	INTEGER,
	"day"	INTEGER
)

Here is our PHP backend.

json.php

<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$db = new SQLite3('chart.db');
$results = $db->query('SELECT * FROM dataset');
$json = array();

while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
   $json[] = $row;
}

echo json_encode($json);

Do not forget to enable CORS with Allow-Origin: * just same as in example code.

Here is our React code.

App.js

import React from 'react';
import { LineChart, Line, CartesianGrid, XAxis, YAxis } from 'recharts';

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      error: null,
      isLoaded: false,
      data: [],
    }
  }

  componentDidMount() {
    fetch('http://localhost/json.php').then(res => res.json()).then((result) => {
      this.setState({ isLoaded: true, data: result });
    },
      (error) => {
        this.setState({ isLoaded: true, error });
      }
    );
  }

  render() {

    if (this.state.error) {
      return <div>Error: {this.state.error.message}</div>;
    } else if (!this.state.isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <LineChart width={600} height={300} data={this.state.data} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}>
          <Line type="monotone" dataKey="temperature" stroke="#8884d8" />
          <Line type="monotone" dataKey="humidity" stroke="#8884d8" />
          <CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
          <XAxis dataKey="year" />
          <YAxis />
        </LineChart>
      );
    }
  }
}