Home > database >  Multiple tooltips not showing correctly in react
Multiple tooltips not showing correctly in react

Time:02-11

I am working with react D3 charts, and I have created charts and it is working fine.

What I have done

  • I have several charts which are updating with in some time intervals, something like live data
  • So here to achieve this I out use effect and updating my charts every second, and my data in charts updates correctly.
  • I have given one tooltip on hover over the the bar, so that user can check the data for each bar or line.

Using below code to show the tooltip

.on("mousemove", function (event, d) {
    // this whole code is when I hover that perticular bar
    d3.select(this)
      .transition()
      .duration("50")
      .attr("opacity", 0.6)
      .attr("x", (a) => xScaleBars(a.timeline) - 3)
      .attr("width", xScaleBars.bandwidth()   6)
      .style("filter", "url(#glow)");

    div.transition().duration(50).style("opacity", 1);
    div
      .html(
        `</text><text"></br> value :  ${d.dataToShow}
        <br/>
        </text><text"></br> Month :  ${d.month}
        `
      )

      .style("left", event.pageX - 58   "px")
      .style("top", event.pageY - 140   "px");
  })
  .on("mouseout", function (d, i) {
    // this is when I move cursor out of that bar
    d3.select(this)
      .transition()
      .duration("50")
      .attr("width", xScaleBars.bandwidth())
      .attr("x", (a) => xScaleBars(a.timeline))
      .style("filter", "none")
      .attr("opacity", "1");
    div.transition().duration("50").style("opacity", 0);
  })

Issue I am facing

  • The issue is when I hover over one chart component it shows the tooltip, and than when I hover over the other both shows at the same time. It shows Like this.

  • What I am trying to do is to show the tooltip when I hover the one bar of any chart and than hide it,I tried below code

d3.select("svg").selectAll(".tooltipCHart").remove();

But it doesn't resolve my issue, I think I am missing some small part

here is my code sandbox which I tried

CodePudding user response:

The problem is that you're creating a new tooltip div every time you re-render the chart.

A better approach is to have a hidden tooltip div in the beginning (in the render / return from your function component) and then just modify its contents and style (opacity: 1) on mouseover and mouseout. Keep track of the tooltip div using a ref.

See working codesandbox (I only modified chart1, you can make similar changes to chart2)

  • Related