Code: Chart.js in your React App
I just had the experience of working with Chart.js while finishing up my final project for my coding bootcamp…and it was actually a lot more fun than I was expecting. Here are some key things to get you started with your charts!
1. Use Chart.js version 2
There are currently 2 versions of Chart.js — make sure to use version 2 with your react app. Your first step after creating your react app is to install Chart.js by typing the following command into your command line:
2. Importing the Charts
The next step is simply importing your charts into your react app within their necessary components. See an example of the code below
- Below are some of examples of the charts that you can play with and the link to the documentation here:
3. Props (Data & Options)
The two main props that our chart is going to take: the data prop and options prop. As you may have guessed the data is going to hold what will be rendered on the chart. The options prop is going to allow you to manipulate the chart. Alright let’s break down what this means with an example from my own app.
- Data Props: Our data props is going to hold the data and the structure of our chart. In my app I was building a mood tracker that took in the users emotion / mood of the day and displayed them on a horizontal bar graph.
- If you see below we have an 3 arrays. The first is the moods array — holds my data points. The second are the labels that will be shown on the y axis of my bar graph — and the third is the the data set that will call the moodsArray and host things such as the “label” and the different colors you want to represent each bar.
- But, remember this is only the first component of our horizontal bar graph and all of this information has to be called within our data object within our render method. See how I have written it below:
- Options Props: The options props is going to allow us to manipulate the position of the different components of the chart. In my example below I have highlighted the options prop — just for clarity. It is going to hold the positioning for the title and the legend. In my example I have the title displaying true — the text which will display as the title of my chart and font size. As for our legend I have displayed it as true and kept the position to right.
- One thing to note is the maintainAspectRaton — if we set it true chart.js it will automatically calculate the height and the width and set it to its 2:1 default setting. If you want to add in your own height and width options — you can set it to false and add them in above your options prop.
4. Now…the finale
This is what your final product should look like.. :)