Saturday 30 April 2022

Custom edge detection for React tooltip causes page to "flash" occasionally

So I created simple edge detection for a tooltip that is part of a charting library. I can't use tooltips that already have implemented edge detection (like MUI tooltip) because the charting software only allows HTML tooltips, so I was left to create a React component that has edge detection for RIGHT side of screen only. Since the tooltip always opens to the right, I just have to take care of the right side.

So when the hover is close to the edge, the tooltip checks how close it is to the edge, then I use CSS offset to place the tooltip at a point away from the right side of the screen.

The component looks like this:

export const MyTooltip = ({ children }) => {

  useEffect(() => {
    const container =
      document.getElementById('tooltip');

    if (container) {
      const x = container.getBoundingClientRect().x;

      if (x > window.outerWidth - 200) {
    container.style.left = 'auto';
        container.style.right = '0';
        container.style.transform = `translateX(${
          window.outerWidth - x - 40
        }px)`;
      }
    }
  }, []);

  return (
    <TooltipStyle>
      <div id="tooltip" className="custom-tooltip">
        {children}
      </div>
    </TooltipStyle>
  );
};

TooltipStyle is a styled component that has CSS for the .custom-tooltip class for the background, padding, etc. 200px is the width of the tooltip in all instances and 40px is the padding.

The problem: Occasionally, when the tooltip renders in the DOM, the page "flashes" for a split second. It's very unsightly. I know it's because of the code in the useEffect hook that actually sets the offset of the tooltip, but I'm not certain about what a good solution would be.

Any help is much appreciated! Thanks.



from Custom edge detection for React tooltip causes page to "flash" occasionally

No comments:

Post a Comment