Creating a Line Chart with React-Vis

React-Vis is an incredibly configurable charting library open sourced from the folks at Uber. It’s main premise is that it provides D3 functionality while still using React component and props. This is great given the fact that React is a widely popular view framework used by many frontend developers. D3, on its own however, has a bit of learning curve. Let’s see how quickly we can spin up a line chart with React-Vis. Ok, let’s start.

Much like in middle school algebra, React-Vis line charts are composed of a familiar set of components, namely: horizontal and vertical grid lines, an x-axis, a y-axis, and the actual line to be drawn on the chart. To compose a line chart, we’ll first need to import the wrapper component for our chart from the react-vis library in addition to the css styling. This component looks like the following:

import ‘../node_modules/react-vis/dist/style.css’; // css styling from the react-vis node module
<XYPlot height={400} width={400} />

Please note, this component must be passed both height and width props. Having imported our wrapper component, we can now import the gridlines, as well as our x & y axes. They look like this:

<VerticalGridLines />
<HorizontalGridLines />
<XAxis />
<YAxis />

Simple enough right? Now let’s create our chart with it’s corresponding grid:

<XYPlot height={400} width={400}>
<VerticalGridLines />
<HorizontalGridLines />
</XYPlot>

Ok sweet! Now, in order to display a line on this chart, we’ll need to import our final component, called a LineSeries.

<LineSeries />

This component will take a single property called data, which will be passed an array of objects with x & y properties.

const data = [{x: 0, y: 8},
{x: 1, y: 5},
{x: 2, y: 4}]
<LineSeries data={data} />

With this, we can now finalize our React-Vis line chart by adding in our <LineSeries> component like so:

const data = [{x: 0, y: 8},
{x: 1, y: 5},
{x: 2, y: 4}]
<XYPlot height={400} width={400}>
<VerticalGridLines />
<HorizontalGridLines />
<XAxis />
<YAxis />
<LineSeries data={data} />
</XYPlot>

Add there you have it! Our first React-Vis Line Chart… with data! Imagine the possibility of pulling your data from your own backend, or maybe using WebSockets to feed data to a chart in real-time. Pretty neat right? If this interests you, please give the React-Vis documentation a glance. There are many other charts available, and each chart is highly configurable based on your respective use case. Anyways, that’s all for now. Thanks for reading, peace!