Categories
React

React Line Chart Example with Recharts

Simple line chart example in React with using Recharts.

After creating our project, please install Recharts.

npm install recharts 

json.php

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

$string = 
'[{"year":"1881", "uv": 4000, "pv": 2400, "amt": 2400},
{"year":"1882", "uv": 3000, "pv": 1398, "amt": 2210},
{"year":"1883", "uv": 2000, "pv": 9800, "amt": 2290},
{"year":"1884", "uv": 2780, "pv": 3908, "amt": 2000},
{"year":"1885", "uv": 1890, "pv": 4800, "amt": 2181},
{"year":"1886", "uv": 2390, "pv": 3800, "amt": 2500},
{"year":"1887", "uv": 3490, "pv": 4300, "amt": 2100}]';

echo json_encode($string);

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: JSON.parse(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="uv" stroke="#8884d8" />
          <CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
          <XAxis dataKey="year" />
          <YAxis />
        </LineChart>
      );
    }
  }
}