0Pricing
React Academy · Lesson

Tooltips & Dropdown Menus with Portals

Use portals to render tooltips and dropdowns that escape overflow-hidden containers.

Tooltips & Dropdown Menus with Portals is a free React Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

In this lesson you will build tooltip and dropdown components that use React Portals to render in document.body, escaping parent overflow-hidden and z-index stacking context constraints.

The Overflow Problem

A tooltip positioned relative to its trigger button will be clipped if any ancestor has `overflow: hidden` or `overflow: scroll`. Moving the tooltip to document.body via a portal solves this completely.

Positioning Strategy

To position a portal-rendered tooltip correctly, measure the trigger element's bounding rectangle with `getBoundingClientRect()` and compute absolute coordinates that account for scroll position.
const rect = triggerRef.current.getBoundingClientRect();
const top = rect.bottom + window.scrollY + 8;
const left = rect.left + window.scrollX;

Tooltip Component

Build a Tooltip that wraps its children, attaches a ref to the trigger, and portals a positioned tooltip box when hovered.
function Tooltip({ content, children }) {
  const [visible, setVisible] = useState(false);
  const [pos, setPos] = useState({ top: 0, left: 0 });
  const ref = useRef();

  const show = () => {
    const r = ref.current.getBoundingClientRect();
    setPos({ top: r.bottom + window.scrollY + 4,
             left: r.left + window.scrollX });
    setVisible(true);
  };

  return (
    <span ref={ref} onMouseEnter={show} onMouseLeave={() => setVisible(false)}>
      {children}
      {visible && createPortal(
        <div style={{ position:'absolute', top: pos.top, left: pos.left }}
             className="tooltip">{content}</div>,
        document.body
      )}
    </span>
  );
}

Updating Position on Scroll & Resize

If the user scrolls while a tooltip is visible, its position becomes stale. Listen to `scroll` and `resize` events to recompute the position or close the tooltip.
useEffect(() => {
  if (!visible) return;
  const update = () => setVisible(false);
  window.addEventListener('scroll', update, true);
  window.addEventListener('resize', update);
  return () => {
    window.removeEventListener('scroll', update, true);
    window.removeEventListener('resize', update);
  };
}, [visible]);

Dropdown Menu Architecture

A dropdown menu follows the same pattern as a tooltip. The trigger button shows/hides the menu, the menu renders via a portal, and a click-outside handler closes it.

Click-Outside Handler

Use a `mousedown` listener on `document` to detect clicks outside the menu. Compare the click target against the menu and trigger refs to decide whether to close.
useEffect(() => {
  if (!open) return;
  const handler = (e) => {
    if (!menuRef.current?.contains(e.target) &&
        !triggerRef.current?.contains(e.target)) {
      setOpen(false);
    }
  };
  document.addEventListener('mousedown', handler);
  return () => document.removeEventListener('mousedown', handler);
}, [open]);

Keyboard Navigation in Dropdowns

Implement ArrowDown/ArrowUp to move between menu items, Enter to select, and Escape to close. Track the focused index in state and programmatically call `.focus()` on the menu items.

Using a Positioning Library

For production, use **@floating-ui/react** (formerly Popper.js). It handles flip (repositioning when near viewport edges), shift (keeping the tooltip visible), and arrow positioning automatically.
import { useFloating, flip, shift } from '@floating-ui/react';

const { refs, floatingStyles } = useFloating({
  middleware: [flip(), shift()],
});

Accessibility: ARIA for Tooltips

For tooltips, add `role='tooltip'` to the tooltip element and `aria-describedby` pointing to the tooltip's id on the trigger. This lets screen readers announce the tooltip content.
<button aria-describedby="tip1">Hover me</button>
{visible && createPortal(
  <div id="tip1" role="tooltip">Helpful text</div>,
  document.body
)}

Quick Check

How do you calculate the correct screen position for a portal-rendered tooltip?

Recap

Portals enable tooltips and dropdowns to escape overflow-hidden parents. Measure the trigger with getBoundingClientRect, add scroll offsets for absolute positioning, close on outside click and scroll, and add ARIA attributes for accessibility.

Course Complete

Congratulations! You finished **Portals & Modals in React**. You can now build accessible, correctly positioned modals, tooltips, and dropdowns that escape any CSS stacking constraints.

Frequently asked questions

Is the “Tooltips & Dropdown Menus with Portals” lesson free?

Yes — the full text of “Tooltips & Dropdown Menus with Portals” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Tooltips & Dropdown Menus with Portals”?

Use portals to render tooltips and dropdowns that escape overflow-hidden containers. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Tooltips & Dropdown Menus with Portals” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Are React Portals?
  2. Building a Modal Component with Portals
  3. Handling Focus & Keyboard Traps in Modals
  4. Tooltips & Dropdown Menus with Portals
← Back to React Academy