I'm trying to add a tooltip each time when hovering circles in my line chart. As you can see in the picture below tooltip is exist in dom but I can't display it. Here I recreated my problem in sandbox:
const tooltip = d3
.select(d3Chart.current)
.append("div")
.attr("class", "tooltip")
.style("opacity", "0")
.style("background-color", "red")
.html(`<p>test</p>`);
const mouseover = function (d) {
console.log("tooltip");
tooltip.transition().duration(200).style("opacity", 0.9);
};
svg
.append('g')
.selectAll('dot')
.data(data)
.enter()
.append('circle')
.attr('cx', function (d) {
return x(d.date);
})
.attr('cy', function (d) {
return y(d.balance);
})
.attr('r', 5)
.attr('fill', '#69b3a2')
.on('mouseover', mouseover);
CodePudding user response:
I followed this article, and you just need to move the div outside the svg
- create a ref to select the tooltip div
const tooltipRef = useRef();
- add it to the HTML
...
</button>
<div className="tooltip" ref={tooltipRef} />
<svg id="chart" ref={d3Chart}></svg>
...
- And change its style on the mouse events
const mouseover = function (event, d) {
console.log(d);
const tooltipDiv = tooltipRef.current;
if (tooltipDiv) {
d3.select(tooltipDiv).transition().duration(200).style("opacity", 0.9);
d3.select(tooltipDiv)
.html(d.balance)
// TODO: some logic when the tooltip could go out from container
.style("left", event.pageX "px")
.style("top", event.pageY - 28 "px");
}
};
const mouseout = () => {
const tooltipDiv = tooltipRef.current;
if (tooltipDiv) {
d3.select(tooltipDiv).transition().duration(500).style("opacity", 0);
}
};
...
.attr("fill", "#69b3a2")
.on("mouseover", mouseover)
.on("mouseout", mouseout);
https://codesandbox.io/s/youthful-cloud-tsu6sj?file=/src/App.js
Notice there are some styles for the tooltip in styles.css