[Chartjs]-Custom tooltip opacity always 1

1👍

Just to clarify for any other person who needs help on this.

When you create your handle for a custom toolbar, you need to pay attention to not overwrite the this(scope) object. Try with arrow function and remove the bind, the fn will get automatically the new scope and the opacity will be update when you move out from a chart bar/line etc.

The same issue will happen with the legend if you try to overwrite the onClick function using inline arrow function or functions. Some examples bellow.

_tooltip = (tooltipModel) => {
...
}
_legendOnClick = (ev) => {
    ev.preventDefault()
}
render() {
    const defaultOpt = {
      legend: {
        onClick: this._legendOnClick
      },
      tooltips: {
        enabled: false,
        custom: this._tooltip,
        mode: 'index'
      }
    }
}

If you want to improve perfomance, you should remove the defaultOpt from the render method.

That’s

0👍

Instead of this:

intersect: false,
custom: (tooltipModel) => {
  if (tooltipModel.opacity === 0) {

use this workaround:

intersect: false,
custom: function(tooltipModel){
  let hit=this._active[0].inRange(this._eventPosition.x, this._eventPosition.y);
  if (tooltipModel.opacity === 0 || !hit) {

make sure not to use arrow function to keep ‘this’.

In my case the root of the problem was that I defined the ‘options’ object in the render function of my component along with the ‘custom’ tooltip handler and called a setState from the inside of it – which caused an other render call immediately. This broke down the tooltip handling of chart.js. Moving the handler outside of the render function solved it without needing the above workaround.

Leave a comment