clearScreen clearScreen - 1 year ago 299
React JSX Question

Allow display of multiple data attributes in tooltip of Chart.js

I am currently working with Chart.js (react version), and I am unable to figure out this problem. I am using a bar chart to display the data. By default, the tooltip only shows the current height of the corresponding bar.

My requirement:

I have data that is available in json format with the following attributes

value1: "",
value2: "",
value3: ""

The height of the bar in the bar chart should be decided by value1 attribute. When we hover on a particular bar, the tooltip should show all information of all three attributes.

I am able to get the graph for only value1. I have looked into the tooltip configuration available in the docs, but could not achieve the requirement.

(I am using react-chartjs)
How do I do this? Thanks in advance

Answer Source

react-chartjs currently depends on Chart.js v1.1.1 - which does not allow the multiple lines in tooltip.

  1. Tweaking the Chart.js file

(this method is not recommended, its only a hack)If you 'have' to use react-chartjs, you can do the following. You can send a custom tooltip template as an option (they use John Resig's micro templating: see it here)

options = {
    tooltipTemplate: "<%=label%>:<%= value %><%\n%><%=value1string%>:<%= value1%><%\n%><%=value2string%>:<%= value2 %>",

But wait, for this method, there are many catches (:P and you follow them all to get it working).

  • The data value1, value1string, value2, value2string have to be global variables for the function in the file Chart.js to access them.

  • If you look at the micro templating engine in the above mentioned blog, you can see that '\n' character is replaced by a " " (space). So the above tooltip template will give all the data in one line. To get the intended behaviour, you need to modify the code in the source file from

(in Chart.js file)

 .replace(/[\r\t\n]/g, ” “)


.replace(/[\r\t]/g, ” “)
  1. Other third-party libraries

There are many other third-party libraries that do what is required.

Using react-chartjs-2. This is a wrapper on Chart.js v2.x. You can use the callbacks in option provided by Chart.js to achieve it. See this example for usage.

var options={
    tooltips: {
        mode: 'label',
        callbacks: {
            afterLabel: function() {
                return 'whatever you want to display';

Using fusioncharts. The library is actually pretty neat and give a very good control over the elements in a plot. You can easily configure the tooltip to act as you want. The only downside of this library is, it's free only for person use.

Using react-d3-tooltip. This library also gives a good amount of control over the elements, go through the docs. You can customize the tooltip as you want.

Hope it helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download