How to create a bar chart with React

In this post we will create a bar chart component with React and use it to display an array of objects with x and y properties. We will use react-vis library to do this.

This is what our finished bar chart will look like.

bar chart

React-vis is an open source library for displaying all kinds of visual representations of data. It can do very many things including complex graphs with complex datasets. When you open up the documentation, it can be a bit overwhelming and hard to find how to exactly create a basic bar chart. So we will create just a basic bar chart that will do the job and you can tweak it more if you need to.

I am using yarn for managing packages. You can download yarn from here https://yarnpkg.com/en/docs/install . If you prefer npm instead, just substitute the yarn commands with corresponding npm commands.

We will create an example project from scratch to play around with react-vis. I decided to use create-react-app for this and in the matter of fact the react-vis documentation also offers instructions how to do this (https://uber.github.io/react-vis/documentation/getting-started/creating-a-new-react-vis-project). If you’d like to use your existing project, you can just skip the create-react-app part and run “yarn add react-vis” in your project directory.

First, if you haven’t done so already, we install create-react-app “npm install -g create-react-app”.

Then we create our project and install react-vis to it.

1create-react-app my-barchart-app
2cd my-barchart-app
3yarn add react-vis

Now we are ready for some charts! Let’s create a new file and name it MyBarChart.js. Then import React and add the following code to it.

1// MyBarChart.js
2import React from "react";
3
4class MyBarChart extends React.Component {
5  render() {
6    const data = this.props.data;
7    const chartWidth = 800;
8    const chartHeight = 500;
9    const chartDomain = [0, chartHeight];
10    return <div>barchart!</div>;
11  }
12}
13
14export default MyBarChart;

Ok so we have a component that renders div with text “barchart!”. We also defined some variables in the render method. data-variable will represent the dataset we want to render, it will be passed to the component as props. chartWidth and chartHeight will be used to set the width and height of the chart. chartDomain will be used to set the yDomain-prop of the bar chart. yDomain is an array with two numbers. First number will indicate the value of the lowest point on the y-axis (bottom of the chart) and the second number will indicate the value of the highest point on the y-axis (top of the chart). We will use 0 for the first number, so that the y-axis starts from 0, and chartHeight for the second value.

Next up let’s import the MyBarChart component to our app and render it. Our App-component should look something like this.

1// App.js
2import React, { Component } from "react";
3import "./App.css";
4import MyBarChart from "./MyBarChart";
5class App extends Component {
6  render() {
7    return (
8      <div className="App">
9                <MyBarChart />
10             {" "}
11      </div>
12    );
13  }
14}
15export default App;

Ok cool, we have our component rendering “barchart!”. Let’s actually add the bar chart now!

We are going to use XYPlot component provided by react-vis. It will act as a wrapper for all the other components we are going to use for the bar chart.

React-vis uses different Series components for displaying a chart. For bar chart we will use BarSeries components and as we want our bars to be vertical, we’ll use VerticalBarSeries component. If we wanted horizontal bars we’d use (surprise) HorizontalBarSeries.

VerticalBarSeries component will draw the rectangles (=bars). In minimum it only requires a data-prop to be passed to it. The data object should be an array containing objects for each bar.

The objects should have x- and y-keys. I created an example dataset that we will use. We will create a data.json file to our src folder and copy paste the json data shown below.

1[
2  { "y": 100, "x": "Jan" },
3  { "y": 112, "x": "Feb" },
4  { "y": 230, "x": "Mar" },
5  { "y": 268, "x": "Apr" },
6  { "y": 300, "x": "May" },
7  { "y": 310, "x": "Jun" },
8  { "y": 315, "x": "Jul" },
9  { "y": 340, "x": "Aug" },
10  { "y": 388, "x": "Sep" },
11  { "y": 404, "x": "Oct" },
12  { "y": 442, "x": "Nov" },
13  { "y": 447, "x": "Dec" }
14]

Now we can import this data in our App-component and pass it to the MyBarChart-component.  After this our App-component and MyBarChart-component should look like this.

1// App.js
2import React, { Component } from "react";
3import "./App.css";
4import MyBarChart from "./MyBarChart";
5import data from "./data.json";
6
7class App extends Component {
8  render() {
9    return (
10      <div className="App">
11                <MyBarChart data={data} />
12             {" "}
13      </div>
14    );
15  }
16}
17
18export default App;
1// MyBarChart.js
2import React from "react";
3import { XYPlot, VerticalBarSeries } from "react-vis";
4
5class MyBarChart extends React.Component {
6  render() {
7    const data = this.props.data;
8    const chartWidth = 800;
9    const chartHeight = 500;
10    const chartDomain = [0, chartHeight];
11    return (
12      <XYPlot
13        xType="ordinal"
14        width={chartWidth}
15        height={chartHeight}
16        yDomain={chartDomain}
17      >
18                        <VerticalBarSeries data={data} />
19                   {" "}
20      </XYPlot>
21    );
22  }
23}
24
25export default MyBarChart;

Now when you save your files and view the app on browser, you should see some nicely rendered bars.

Ok that’s cool, but we want to also show the x- and y-axis. For this react-vis provides XAxis- and YAxis-components. They are just placed inside the XYPlot component and boom we have x- and y-axis on our chart.

Our bar chart is starting to look good. One more thing we can do is to display the value of each bar on top of the bar. React-vis comes with LabelSeries component that enables us to display labels for each datapoint. In order for LabelSeries to work with our data, we need to add label-key to our data and pass it to the LabelSeries component.

By default LabelSeries will automatically calculate the position for the label based on the position of the datapoint on the chart. For example if we are near the right hand side of the chart, the label will be displayed left from the datapoint or if we are near the bottom of the chart the label will be displayed on top of the datapoint.

For our chart, we don’t want the automatic positioning but we want the label to always be on top of the datapoint and horizontally centered. To achieve this we use LabelSeries props labelAnchorX and labelAnchorY. labelAnchorX value will be “middle” and labelAnchorY value will be “text-after-edge”. More info for about other values for these props can be found from the docs https://uber.github.io/react-vis/documentation/series-reference/label-series .

This is what our finished MyBarChart-component should look like.

1// MyBarChart.js
2import React from "react";
3import {
4  XYPlot,
5  XAxis, // Shows the values on x axis
6  YAxis, // Shows the values on y axis
7  VerticalBarSeries,
8  LabelSeries,
9} from "react-vis";
10
11class MyBarChart extends React.Component {
12  render() {
13    const data = this.props.data;
14    const chartWidth = 800;
15    const chartHeight = 500;
16    const chartDomain = [0, chartHeight];
17    return (
18      <XYPlot
19        xType="ordinal"
20        width={chartWidth}
21        height={chartHeight}
22        yDomain={chartDomain}
23      >
24                        <XAxis />
25                        <YAxis />
26                        <VerticalBarSeries data={data} />
27                        <LabelSeries
28          data={data.map((obj) => {
29            return { ...obj, label: obj.y.toString() };
30          })}
31          labelAnchorX="middle"
32          labelAnchorY="text-after-edge"
33        />
34                    
35      </XYPlot>
36    );
37  }
38}
39
40export default MyBarChart;

Conclusion

Creating charts with React and react-vis is pretty straight forward once you know your way around the react-vis components. There is a lot more you can do with react-vis and if you work with or are interested about data visualisation, for sure go ahead and check out the documentation for more complex examples.

You can find the complete source code for this tutorial from GitHub: https://github.com/tumetus/react-vis-bar-chart

Charts are great way to visualise data. If you wish to learn more about different kind of charts, I recommend you check out this blog post.


Read next:
If you want to learn more, make sure to subscribe on Youtube!

Subscribe to the newsletter