There’s a great number of charting libraries (e.g. Highcharts, D3 etc.) which are great if you want to quickly get a chart up and running. However, customising them exactly to your needs isn’t always straightforward. Also, if you already have a React project, it’s not always easy to integrate a non-React charting library.
In this tutorial we’ll learn how to create this bar chart using just React:
1. Create project
There’s several different ways to create a React based project so either use your usual approach and adapt this tutorial to your particular needs, or follow along on Codepen.
The main thing to make sure is that the two React libraries
react-dom are included. For example if using Codepen, include these two files:
2. Create BarChart component
Our project will consist of two components:
BarChart for the bar chart and
BarGroup for a group containing:
- a single bar
- a name label and
- a value label
Let’s start by creating a simple BarChart component:
We can see that we’ve added an array of data to the state object and our
render function returns an SVG element that’ll contain the chart.
3. Create BarGroup component
We’ll now make a
BarGroup component which’ll return an SVG group containing a rect element (for the bar) and a couple of text elements (for the two labels):
We’ll need to position the two labels (the name label will go to the left of the bar and the value label at the end of the bar) and size the rectangle:
Notice that we’ve defined this as a pure function component.
4. Render BarGroup components
Now let’s return to the BarChart component and use
map to translate our array of data into an array of
g elements each of which contains a
Note that we transform each
g element vertically according to the index
i. We also pass the array element
barHeight as props.
5. Render the BarChart component
We’ve now ready to render the BarChart component in our webpage. Assuming our HTML is something like:
we can use:
to render our bar chart:
6. Add CSS style rules
No prizes for guessing that we’re missing some CSS styling on our bar chart! The main things we need to do are:
- add a nice font (we’ll use Google’s Lato font)
- align the text labels using
- tweak the font sizes
Our chart now looks much better!
7. Add a hover effect
Finally we’ll add a hover effect for when the user hovers their mouse over a bar:
Now when we hover over a bar the hovered bar’s labels change in weight or size and the remaining bars fade:
8. We’re done!
This tutorial has shown how a simple bar chart can be created with just React without the use of a charting library. The advantage of this approach is that you have complete control over how the chart looks and also have no issues integrating a 3rd party library such as Highcharts or D3.
Obviously it’ll require more effort if you require features such as tooltips, responsivity and transitions but for simple charts this approach may be sufficient.
You can see the complete code on Codepen below.