0

Problem Statement: I am trying to build chartJs in ReactJs. I want to make customized tooltip with callback function or similar option so I can display details inside tooltip. Is there a way to make it possible?

Output for ChartJs tooltip

My code: Render Function

render() {
  return (
    <HorizontalBar
      data={this.state.allData}
      width={200}
      height={100}           

      options={{
                 
      tooltips: {
        // Disable the on-canvas tooltip
        enabled: false,
        callbacks: {
          label: function(tooltipItem, data) {
              console.log("pront ---- ", data)
          },
        },
                
        custom: function(tooltipModel, data) {
          // Tooltip Element
          var tooltipEl = document.getElementById('chartjs-tooltip');

          // Create element on first render
          if (!tooltipEl) {
              tooltipEl = document.createElement('div');
              tooltipEl.id = 'chartjs-tooltip';
              tooltipEl.innerHTML = '<table></table>';
              document.body.appendChild(tooltipEl);
          }

          // Set Text
          if (tooltipModel.body) {
            var titleLines = tooltipModel.title || [];
            var bodyLines = tooltipModel.body.map(getBody);

            var innerHtml = '<thead>';

            titleLines.forEach(function(title) {
              innerHtml += '<tr><th>' + title + '</th></tr>';
            });
            innerHtml += '</thead><tbody>';

            bodyLines.forEach(function(body, i) {
              var colors = tooltipModel.labelColors[i];
              var style = 'background:' + colors.backgroundColor;
              style += '; border-color:' + colors.borderColor;
              style += '; border-width: 2px';
              style += '; min-width: 5px; width: 10px; height: 10px; display: block;';
              var span = '<span style="' + style + '"></span>';
              innerHtml += '<tr><td>' + span + body + '</td></tr>';
            });
            innerHtml += '</tbody>';

            var tableRoot = tooltipEl.querySelector('table');
            tableRoot.innerHTML = innerHtml;
          }
        }
      },
                  
    }}
    />
  );
}

I want display multiple lines in tooltip with HTML UI.

  • what issue your facing in custom tooltip ? – Raj Kumar Aug 26 '20 at 09:39
  • @RajKumar I have updated required output image in question. I need to display json data inside Tooltip. – Rohit Desai Aug 27 '20 at 10:57
  • in the image, its stacked bar, you need like that or normal bar chart ? and what is the bar data `allData` your passing, based on that only we can identify the issues where it occuring for fix – Raj Kumar Aug 27 '20 at 11:07

0 Answers0