Looking to start some graphing in react-vis and am wondering what's the best approach for pushing data from a json to state so I can access the state data from graphing. Below is my test json:
[
{
"day": "1",
"flights":"58",
"passengers": "6076"
},
{
"day": "2",
"flights": "78",
"passengers": "7089"
},
{
"day": "3",
"flights": "101",
"passengers": "9760"
}
]
I essentially want to push "day" and "flights" into the data array to mimic the sample provided by react-vis. Below is my code:
App.js
//import logo from './logo.svg';
//import './App.css';
import React, { Component } from 'react';
import my_data from './data/csvjson.json';
import {XYPlot, XAxis, YAxis, HorizontalGridLines, LineSeries,
VerticalGridLines, LineMarkSeries} from 'react-vis';
import '../node_modules/react-vis/dist/style.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data:[]
}
}
//react vis documentation points to data being an object like so:
//sample data
//data:[
// {x: 0, y: 8},
// {x: 1, y: 5},
// {x: 2, y: 4}
// ]
render() {
return (
<div>
<XYPlot width={400} height={300}><XAxis/><YAxis/>
<HorizontalGridLines />
<VerticalGridLines />
<LineMarkSeries data={this.state.data} />
</XYPlot>
</div>
);
}
}
export default App;
You need to preprocess my_data
and store it in the state. There should be one function which maps over the my_data
and return the array with ojects having x and y properties {x: day, y: flight}
.
import React, { Component } from 'react';
import { render } from 'react-dom';
import my_data from './data/csvjson.json';
import {XYPlot, XAxis, YAxis, HorizontalGridLines, LineSeries,
VerticalGridLines, LineMarkSeries} from 'react-vis';
const processData = (data) => {
return data.map(e => ({
x: e.day,
y: e.flights
}));
};
class App extends Component {
constructor() {
super();
this.state = {
data: processData(my_data)
};
}
render() {
return (
<div>
<XYPlot width={400} height={300}><XAxis/><YAxis/>
<HorizontalGridLines />
<VerticalGridLines />
<LineMarkSeries data={this.state.data} />
</XYPlot>
</div>
);
}
}
render(<App />, document.getElementById('root'));
I also did it on stackblitz, you can check the live demo there: https://stackblitz.com/edit/react-abkc1j