How would you build a tooltip using a Portal so it always appears above everything else on the page?
Short answer
A tooltip rendered inside a deeply nested component can sometimes get visually cut off by a parent element with hidden overflow.
Advertisement
AModel answer
A tooltip rendered inside a deeply nested component can sometimes get visually cut off by a parent element with hidden overflow. Rendering the tooltip through a Portal, directly attached near the very end of the page's body, avoids this problem entirely, since it is no longer restricted by any parent's layout or overflow settings.
function Tooltip({ text, targetRef }) {
const position = targetRef.current?.getBoundingClientRect();
if (!position) return null;
return createPortal(
<div style={{ position: 'absolute', top: position.bottom, left: position.left }}>
{text}
</div>,
document.body
);
}Real-world example
A data table with hidden overflow settings used to cut off tooltips shown on cells near the edge, until the team fixed it by rendering the tooltip through a Portal attached directly to the document body instead.
Likely follow-ups
- How do you calculate the correct position for a tooltip rendered through a Portal?
- What happens to a Portal's tooltip if the page is scrolled while it is open?
Related topics