Sub topic 9
Tooltips and popovers
This chapter assumes you know createPortal, the modal pattern from the earlier chapters, and basic useRef, useState and useEffect usage. You should also know what position: fixed does and that getBoundingClientRect() returns an element's position relative to the viewport.
Why tooltips need portals
A tooltip or popover is a small floating layer attached to a trigger element. Triggers often sit inside containers that clip or bury the layer:
- A table cell, card or scroll area with
overflow: hiddenoroverflow: autocuts off any child that extends past its edge. - A parent with
transform,filteroropacitybelow 1 creates a stacking context. Az-index: 9999inside it can still render under a sibling elsewhere on the page. - A transformed ancestor also changes what
position: fixedis relative to, so a "fixed" child can move with its parent.
Rendering the floating layer into document.body avoids all three problems. The layer is no longer a DOM descendant of the clipping container.
The positioning problem
Once the layer lives in document.body, CSS can no longer place it relative to the trigger. You have to measure the trigger and position the layer yourself.
A tooltip component
This component measures in useLayoutEffect, so the position is set before the browser paints and the tooltip does not flash at the wrong place.
import { useId, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
function Tooltip({ label, children }) {
const triggerRef = useRef(null);
const [open, setOpen] = useState(false);
const [position, setPosition] = useState({ top: 0, left: 0 });
const tooltipId = useId();
useLayoutEffect(() => {
if (!open) return;
function update() {
const rect = triggerRef.current.getBoundingClientRect();
setPosition({
top: rect.bottom + 8,
left: rect.left + rect.width / 2,
});
}
update();
window.addEventListener('scroll', update, true);
window.addEventListener('resize', update);
return () => {
window.removeEventListener('scroll', update, true);
window.removeEventListener('resize', update);
};
}, [open]);
return (
<>
<span
ref={triggerRef}
aria-describedby={open ? tooltipId : undefined}
onMouseEnter={() => setOpen(true)}
onMouseLeave={() => setOpen(false)}
onFocus={() => setOpen(true)}
onBlur={() => setOpen(false)}
>
{children}
</span>
{open &&
createPortal(
<div
id={tooltipId}
role="tooltip"
style={{
position: 'fixed',
top: position.top,
left: position.left,
transform: 'translateX(-50%)',
}}
>
{label}
</div>,
document.body
)}
</>
);
}Some details worth noting:
- The
scrolllistener uses capture (true) because scroll events do not bubble. Capture also catches scrolling inside nested containers, not only the window. - The effect only attaches listeners while the tooltip is open, and the cleanup removes them. This avoids the stray-listener pitfall.
role="tooltip"plusaria-describedbyon the trigger lets screen readers announce the label. Focus handlers make the tooltip reachable by keyboard.- React's
onFocusandonBlurbubble, so focusing a button inside the span opens the tooltip.
From tooltip to popover
A popover differs from a tooltip in one way that matters: it is interactive and opens on click. That adds two requirements, closing on outside click and closing on Escape.
Closing on outside click has a trap. The popover's DOM node is in document.body, not inside the trigger's wrapper. A check such as wrapper.contains(event.target) treats a click inside the popover as an outside click. Check both nodes:
import { useEffect } from 'react';
function useOutsideClick(refs, onOutside) {
useEffect(() => {
function handlePointerDown(event) {
const inside = refs.some(
(ref) => ref.current && ref.current.contains(event.target)
);
if (!inside) onOutside();
}
document.addEventListener('pointerdown', handlePointerDown);
return () => document.removeEventListener('pointerdown', handlePointerDown);
}, [refs, onOutside]);
}Call it as useOutsideClick([triggerRef, popoverRef], close). Pass a stable array and callback (for example with useMemo and useCallback), or the effect re-subscribes on every render. Combine it with the useEscapeKey hook from the accessibility chapter.
Practical notes
- Positioning near the viewport edge needs flipping logic, for example showing above the trigger when there is no room below. For production use, consider a library such as Floating UI, which handles flipping, shifting and arrows. It also uses portals the same way.
- React events from the portal bubble to the trigger's ancestors. If a card has an
onClickhandler, clicks inside your popover will reach it unless you callevent.stopPropagation(). - Because the tooltip only renders after a user event, it needs no server-rendering guard. A popover that opens by default does.
Exercise
A popover is rendered into document.body through a portal. Your outside-click handler checks only whether the click target is inside the trigger's wrapper element, and the popover closes whenever the user clicks a button inside it. Why does this happen, and how do you fix it?
Show answer
The popover's DOM node is not a descendant of the wrapper, so wrapper.contains(event.target) is false for clicks inside the popover, and the handler treats them as outside clicks. Fix it by also checking the popover's own ref, so the click counts as outside only if the target is in neither the trigger nor the popover.