Sub topic 9
Tooltips and Popovers
This chapter builds a tooltip and a popover on top of createPortal. Both are small floating panels attached to a trigger element, and both have the clipping and stacking problems from the start of the tutorial. They add two new problems: positioning the panel next to its trigger, and dismissing it correctly.
What this chapter assumes
- You can write function components with
useState,useEffect, anduseRef. - You know how
createPortal(children, container)works and that React events bubble through the React tree, not the DOM tree. - You understand
position: fixed,z-index, andoverflow: hidden. - You know what
getBoundingClientRect()returns.
Why floating panels need a portal
A tooltip placed next to its trigger in the DOM breaks in three common situations:
- An ancestor has
overflow: hiddenoroverflow: auto, so the panel is clipped at the ancestor's edge. - An ancestor creates a stacking context (through
transform,opacity < 1,filter, orpositionwithz-index). The panel can never rise above siblings outside that context, whatever z-index you give it. - An ancestor has a
transform, which turnsposition: fixedinto positioning relative to that ancestor instead of the viewport.
Rendering the panel into document.body avoids all three. The panel is then a direct child of the body and is only clipped by the viewport. The React tree is unchanged, so the panel still receives props, state, and context from the component that renders it.
The tradeoff is that you now position the panel yourself. CSS can no longer place it relative to the trigger, because the two are not DOM neighbors.
Tooltip versus popover
The two patterns differ in behavior, and the differences decide which code you need.
| Aspect | Tooltip | Popover |
|---|---|---|
| Content | Short, non-interactive text | Can contain links, buttons, forms |
| Opens on | Hover and keyboard focus | Click or keypress on the trigger |
| Closes on | Mouse leave, blur, Escape | Outside click, Escape, explicit close |
| Focus | Stays on the trigger | Should move into the panel |
| ARIA | `role="tooltip"`, `aria-describedby` | `aria-expanded`, `aria-controls` on the trigger |
A tooltip must never contain interactive content. The pointer leaves the trigger on its way to the panel, which closes the tooltip before the user can click anything.
Shared positioning hook
Both components need to place a panel next to an anchor. Put that logic in one hook.
The hook uses position: fixed coordinates. getBoundingClientRect() returns viewport coordinates, so you can use them directly without adding scroll offsets. The hook runs in useLayoutEffect so that the measurement and the position update happen before the browser paints. With useEffect, users would see the panel flash at its initial position.
import { useLayoutEffect, useState } from 'react';
export function useAnchoredPosition(anchorRef, floatingRef, open, gap = 8) {
const [pos, setPos] = useState({ top: 0, left: 0 });
useLayoutEffect(() => {
if (!open) return;
function update() {
const anchor = anchorRef.current?.getBoundingClientRect();
const floating = floatingRef.current?.getBoundingClientRect();
if (!anchor || !floating) return;
// Prefer above the anchor; flip below if there is no room.
let top = anchor.top - floating.height - gap;
if (top < 0) top = anchor.bottom + gap;
// Center horizontally, then clamp inside the viewport.
const centered = anchor.left + anchor.width / 2 - floating.width / 2;
const maxLeft = window.innerWidth - floating.width - 4;
const left = Math.max(4, Math.min(centered, maxLeft));
setPos({ top, left });
}
update();
window.addEventListener('resize', update);
// Capture phase catches scrolling of any ancestor, not only the window.
window.addEventListener('scroll', update, true);
return () => {
window.removeEventListener('resize', update);
window.removeEventListener('scroll', update, true);
};
}, [anchorRef, floatingRef, open, gap]);
return pos;
}The scroll listener uses the capture phase because scroll events do not bubble. Without true, the panel would follow the window but not a scrollable container that holds the trigger.
The hook flips the panel below the anchor when there is no room above, and clamps it horizontally. This covers most cases. For a full set of placements, collision handling, and arrow positioning, use a library such as Floating UI. It is built on the same measurements.
Building the tooltip
The lifecycle has two renders. The first renders the panel at 0, 0 so it exists and can be measured. The layout effect then measures it and sets the real position before paint.
import { useEffect, useId, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useAnchoredPosition } from './useAnchoredPosition';
export function Tooltip({ label, children }) {
const anchorRef = useRef(null);
const tipRef = useRef(null);
const [open, setOpen] = useState(false);
const id = useId();
const { top, left } = useAnchoredPosition(anchorRef, tipRef, open);
useEffect(() => {
if (!open) return;
function onKeyDown(event) {
if (event.key === 'Escape') setOpen(false);
}
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
}, [open]);
return (
<>
<span
ref={anchorRef}
aria-describedby={open ? id : undefined}
onMouseEnter={() => setOpen(true)}
onMouseLeave={() => setOpen(false)}
onFocus={() => setOpen(true)}
onBlur={() => setOpen(false)}
>
{children}
</span>
{open &&
createPortal(
<div
ref={tipRef}
id={id}
role="tooltip"
style={{
position: 'fixed',
top,
left,
pointerEvents: 'none',
background: '#222',
color: '#fff',
padding: '4px 8px',
borderRadius: 4,
fontSize: 14,
zIndex: 1000,
}}
>
{label}
</div>,
document.body
)}
</>
);
}Several details in this component are deliberate:
onFocusandonBluron the wrapper. React'sonFocusandonBlurbubble, so focus on a button inside the span opens the tooltip. Keyboard users get the same information as mouse users.aria-describedbyonly while open. The id points at an element that only exists while the tooltip is open. A reference to a missing id does nothing useful.pointerEvents: 'none'. The panel never intercepts the pointer, so it cannot cause flicker if it ends up under the cursor.document.bodyinside the render expression. This is safe in this component, because the portal is created only whenopenis true, and that can only happen after a user event in the browser. The server render never reaches that line.- A
useIdidentifier. It is stable between server and client, so it is safe for ARIA references.
Use it like this:
export default function Toolbar() {
return (
<div style={{ overflow: 'hidden', height: 40, transform: 'translateZ(0)' }}>
<Tooltip label="Save your changes">
<button type="button">Save</button>
</Tooltip>
</div>
);
}The container clips its children and creates a stacking context. The tooltip still displays in full, because it lives in document.body.
Building the popover
A popover is interactive, so it needs three things the tooltip does not: toggling by click, dismissal on outside click, and focus management.
import { useEffect, useId, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useAnchoredPosition } from './useAnchoredPosition';
export function Popover({ triggerLabel, children }) {
const buttonRef = useRef(null);
const panelRef = useRef(null);
const [open, setOpen] = useState(false);
const id = useId();
const { top, left } = useAnchoredPosition(buttonRef, panelRef, open);
useEffect(() => {
if (!open) return;
// Tab order: the panel is at the end of <body>, so move focus into it.
panelRef.current?.focus();
function onPointerDown(event) {
const inButton = buttonRef.current?.contains(event.target);
const inPanel = panelRef.current?.contains(event.target);
if (!inButton && !inPanel) setOpen(false);
}
function onKeyDown(event) {
if (event.key === 'Escape') {
setOpen(false);
buttonRef.current?.focus();
}
}
document.addEventListener('pointerdown', onPointerDown);
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('pointerdown', onPointerDown);
document.removeEventListener('keydown', onKeyDown);
};
}, [open]);
return (
<>
<button
ref={buttonRef}
type="button"
aria-expanded={open}
aria-controls={open ? id : undefined}
onClick={() => setOpen((value) => !value)}
>
{triggerLabel}
</button>
{open &&
createPortal(
<div
ref={panelRef}
id={id}
role="dialog"
aria-label={triggerLabel}
tabIndex={-1}
style={{
position: 'fixed',
top,
left,
background: '#fff',
border: '1px solid #ccc',
borderRadius: 6,
padding: 12,
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)',
zIndex: 1000,
}}
>
{children}
</div>,
document.body
)}
</>
);
}The outside-click check must test two nodes
The outside-click handler is a native document listener, not a React handler. Native listeners follow the DOM tree. A click inside the panel has document.body as its DOM parent, not the button, so the panel is not inside any element React considers its parent.
If you only tested buttonRef.current.contains(event.target), every click inside the panel would count as "outside" and close it. Test both nodes, as the code above does.
The reverse also matters. If you used a React onClick on a wrapper to detect clicks, a click in the portal would bubble to that wrapper through the React tree. Which kind of handler you use decides which tree answers the question "is this click inside?".
Why focus moves into the panel
The portal appends the panel at the end of <body>. Pressing Tab from the trigger button moves to the next focusable element in the DOM, which is somewhere else on the page, not the panel. Moving focus into the panel on open fixes this for a popover with a few controls. Returning focus to the button on Escape completes the loop.
For a popover with many controls, you would also handle Tab and Shift+Tab at the panel's edges. The next-chapter-level answer is a focus trap for modals. Popovers are usually non-modal, so most teams accept the simpler approach.
Behavior details worth knowing
- Scrolling. The positioning hook re-measures on scroll, so the panel follows its anchor. For many tooltips on a page, only the open one has listeners, because the hook installs them only while
openis true. - Anchor removal. If the anchor unmounts while the panel is open, the panel unmounts with it, because both are rendered by the same component.
- Parent re-renders. The portal re-renders with its parent like any child. You do not need extra state to keep the panel's content current.
- Anchor resizes. The hook does not observe size changes of the anchor or panel. If content can change size while open, add a
ResizeObserveron both nodes that callsupdate. - Touch devices. There is no hover. Tooltips are best treated as supplementary on touch screens. Put essential information in visible text, or use a popover that opens on tap.
Common mistakes
- Measuring before the panel exists. Calling
getBoundingClientRect()ontipRef.currentin the event handler returnsnullerrors or zero sizes. Measure inuseLayoutEffectafter the portal has rendered. - Using
position: absolutewithout scroll offsets. Absolute coordinates inbodyrequire addingwindow.scrollXandwindow.scrollY. Fixed positioning avoids that, at the cost of re-measuring on scroll. - Putting interactive content in a tooltip. Use a popover instead.
- Leaving
pointer-eventson a tooltip. The panel can sit under the cursor, triggermouseleaveon the anchor, and flicker. - Forgetting Escape. WCAG 1.4.13 requires content that appears on hover or focus to be dismissible without moving the pointer. Escape satisfies this.
Exercise
In the Popover above, a developer replaces the document pointerdown listener with an onClick handler on the component that renders <Popover>, intending to close the popover when the user clicks anywhere outside it. Clicks inside the portal panel then close the popover unexpectedly or fail to behave as intended. Explain why, and say which tree each approach follows.
Show answer
A React onClick on an ancestor follows the React tree. A click inside the portal panel bubbles from the panel to the component that rendered it, even though the panel is in document.body. So that ancestor handler fires for clicks inside the panel too, and it cannot tell "inside" from "outside" by event position alone. The native document listener follows the DOM tree. There, the panel is not inside the button, so you must check contains against both the button and the panel. The fix is to keep the native listener and test both refs, or to stop propagation of the click at the panel so it does not reach the ancestor handler.
Exercise
The tooltip is positioned with useLayoutEffect instead of useEffect. What would a user see if you switched to useEffect, and why does the panel render at 0, 0 first?
Show answer
The panel must exist in the DOM to be measured, so the first render places it at the initial 0, 0 position. useLayoutEffect runs after the DOM update but before the browser paints, so the second render with the correct position replaces the first before the user sees anything. With useEffect, the browser may paint the first render, so the tooltip would briefly flash in the top-left corner before jumping to the right place.