Chartjs-How to make vertical line when hovering cursor (Chart js)

0👍

As LeeLenalee already commented, a pure Chart.js solution is shown in this answer.

With react-chartjs-2, plugins needs to be defined as a separate option, same as data and options. In your case, this could look as follows.

render() {
  return (
    <Line
      data = {
        ...
      }
      plugins = {
        [{
          afterDraw: chart => {
            if (chart.tooltip?._active?.length) {
              let x = chart.tooltip._active[0].element.x;
              let yAxis = chart.scales.y;
              let ctx = chart.ctx;
              ctx.save();
              ctx.beginPath();
              ctx.setLineDash([5, 5]);
              ctx.moveTo(x, yAxis.top);
              ctx.lineTo(x, yAxis.bottom);
              ctx.lineWidth = 1;
              ctx.strokeStyle = 'rgba(0, 0, 255, 0.4)';
              ctx.stroke();
              ctx.restore(); 
            }
          }
        }]
      }
      options = {
        ...
      }
    /> 
  );
}

Leave a comment