How to create a quick React Component with ChartJS 2 and cool customizations (Part 1 of 2)

Carol Darski
Thinkific

--

A couple of weeks ago, I was working on a React project at Thinkific where we needed to implement a chart library that had to be flexible enough to deal with customized tooltips and stylish bars. We decided to go with ChartJS and this motivated me to create this quick tutorial on how we did it. 😄

Let’s start coding 🚀

ChartJS 2 for React

We chose ChartJS 2 as the library for the charts as it’s open source (yay!), has an amazing community around it and it’s also highly customizable.

To use it inside of a React component, we decided to install the package react-chartjs-2 that is simply a React wrapper for the library.

You can install it running:

npm install react-chartjs-2 chart.js --save

Now we are ready to start on our component! ⭐️

With a couple lines of code, we already have a chart with bars 🎉. We can increment this a little bit and make the top bar edges rounded with custom code.

Bars with rounded edges

This one was a little tricky, as ChartJS 2 does not offer an option to set the border radius for each bar so we had to build a custom code.

The code is an override of the draw function from the Rectangle class in the ChartJS. The base code is from here and I adapted it as we only needed the top edges rounded but the bottom would stay the same.

To use this custom code in the previous component, we need to import it and pass the cornerRadius as an option property in the BarChart.

You should now be able to see top rounded edges on your chart! 🎉

To add more customization, you can take a look at available options for bar chart at ChartJS 2 docs.

In the next article, I will show you how to integrate cool custom tooltips with ChartJS 2 to make things a bit more interesting. You can find an example of the chart here: Github repo

If you liked this article, don’t forget the 👏!

--

--

Carol Darski
Thinkific

Sophie’s Mom. Software Engineering Manager @ Routific. Dog lover. Proud feminist ❤