Adding tooltips to SVG.js elements

142 Views Asked by At

What is a recommended way to use tooltips on svg elements in react? Is there some way to reuse my existing tooltips which are react components (I use ant-design tooltips) in there?

const addTooltipToSVGElement = (element: Circle | Line, tooltipText: string, svgContainerId = 'SVGContainer') => {
  const node = element.node
  const tooltip = document.createElement('div')
  tooltip.className = 'ant-tooltip ant-tooltip-placemenet-top'
  // create ant tooltip html
  tooltip.innerHTML = `<div class="ant-tooltip-content"><div class="ant-tooltip-inner" role="tooltip">${tooltipText}</div></div>`

  element.mouseover(function () {
    const svgContainer = document.getElementById(svgContainerId) as Element
    svgContainer?.parentNode?.appendChild(tooltip)
    const { left, top, width } = node.getBoundingClientRect()
    const svgContainerPosition = svgContainer?.getBoundingClientRect() as DOMRect
    const tooltipLeft = left - svgContainerPosition.left + width / 2
    const tooltipTop = top - svgContainerPosition.top - tooltip.offsetHeight
    tooltip.style.left = tooltipLeft + 'px'
    tooltip.style.top = tooltipTop + 'px'
  })

  element.mouseout(function () {
    tooltip.parentNode?.removeChild(tooltip)
  })
}

But it seems to be very imperative and not really reusing ant tooltip rather recreating it. Is there a better way?

0

There are 0 best solutions below