Skip to Content
vitus·labs
Elements

Overlay

Advanced positioning system for dropdowns, tooltips, popovers, and modals.

Overlay is a complete positioning and interaction system for floating UI elements. It handles trigger/content refs, dynamic positioning with viewport edge flipping, event listeners, and nested overlay blocking.

Basic Usage

import { Overlay } from '@vitus-labs/elements'

// Dropdown
<Overlay trigger={<button>Menu</button>}>
  <div>Dropdown content</div>
</Overlay>

// Tooltip on hover
<Overlay
  type="tooltip"
  openOn="hover"
  closeOn="hover"
  align="top"
  trigger={<span>Hover me</span>}
>
  <div>Tooltip text</div>
</Overlay>

Props

Content

PropTypeDescription
triggerReactNode | (props) => ReactNodeTrigger element or render function
childrenReactNode | (props) => ReactNodeContent to show when open
DOMLocationHTMLElementPortal target (default: document.body)
triggerRefNamestringRef prop name for trigger (default: 'ref')
contentRefNamestringRef prop name for content (default: 'ref')

Behavior

closeOn values: 'click' closes on any click (trigger, content or outside), 'clickOnTrigger' only on the trigger, 'clickOutsideContent' on any click outside the content, 'hover' when the pointer (or focus) leaves both trigger and content, and 'manual' only through hideContent.

PropTypeDefaultDescription
isOpenbooleanfalseInitial open state
openOn'click' | 'hover' | 'manual''click'How to open
closeOn'click' | 'clickOnTrigger' | 'clickOutsideContent' | 'hover' | 'manual''click'How to close
closeOnEscbooleantrueClose on ESC key (only the topmost open overlay closes)
hoverDelaynumber100Delay (ms) before hiding on hover leave; bridges the gap between trigger and content
disabledboolean—Closes the overlay and blocks it from opening
onOpen() => void—Called on open
onClose() => void—Called on close

Positioning

PropTypeDefaultDescription
type'dropdown' | 'tooltip' | 'popover' | 'modal' | 'custom''dropdown'Positioning preset
position'absolute' | 'fixed' | 'relative' | 'static''fixed'CSS position
align'top' | 'bottom' | 'left' | 'right''bottom'Primary direction
alignX'left' | 'center' | 'right''left'Horizontal alignment
alignY'top' | 'center' | 'bottom''bottom'Vertical alignment
offsetXnumber0Horizontal margin
offsetYnumber0Vertical margin
throttleDelaynumber200Position recalculation throttle (ms)
parentContainerHTMLElement | null—Custom scroll container. Its scroll repositions the content; its overflow is set to hidden while open (except with closeOn="hover") and restored on close

Render Props

When using render functions (or components), trigger and content receive interaction props. showContent / hideContent are passed only when openOn="manual", closeOn="manual" or closeOn="clickOutsideContent". Plain DOM elements (e.g. trigger={<button>Open</button>}) receive only the ref and ARIA attributes, never component props like active or alignX.

Trigger Render Props

<Overlay
  trigger={(props) => (
    <button ref={props.ref}>
      {props.active ? 'Close' : 'Open'}
    </button>
  )}
>
  <div>Content</div>
</Overlay>
PropTypeDescription
activebooleanWhether content is visible
showContent() => voidOpen the overlay
hideContent() => voidClose the overlay

Content Render Props

<Overlay trigger={<button>Open</button>}>
  {(props) => (
    <div ref={props.ref}>
      Aligned: {props.align} / {props.alignX}
      <button onClick={props.hideContent}>Close</button>
    </div>
  )}
</Overlay>
PropTypeDescription
activebooleanWhether content is visible
alignstringThe align prop as passed
alignXstringResolved horizontal alignment (after any flip)
alignYstringResolved vertical alignment (after any flip)
showContent() => voidOpen
hideContent() => voidClose

Positioning Types

Positioned relative to trigger, below by default. Flips to top if not enough space.

<Overlay type="dropdown" align="bottom" alignX="left">
  ...
</Overlay>

Tooltip

Similar to dropdown but typically used with hover:

<Overlay type="tooltip" openOn="hover" closeOn="hover" align="top">
  ...
</Overlay>

Positioned against the viewport, not the trigger. alignX / alignY pick the edge, and offsetX / offsetY set the distance from it. With the defaults (alignX="left", alignY="bottom") a modal sits at the bottom-left corner, so pass center on both axes to center it:

<Overlay
  type="modal"
  alignX="center"
  alignY="center"
  openOn="click"
  closeOn="clickOutsideContent"
  closeOnEsc
>
  {(props) => (
    <div style={{ background: 'white', padding: 24, borderRadius: 8 }}>
      Modal content
      <button onClick={props.hideContent}>Close</button>
    </div>
  )}
</Overlay>

Custom

type="custom" keeps open/close handling, ARIA and event listeners but does no positioning. Position the content yourself.

Accessibility

  • The trigger gets aria-expanded, aria-haspopup ("dialog" for modal/popover, "menu" for dropdown, "true" otherwise) and aria-controls while open. Tooltip triggers get aria-describedby instead.
  • The content gets an id, plus role="dialog" + aria-modal for modals and role="tooltip" for tooltips.
  • For dropdowns/popovers, closing returns focus to the trigger if focus was inside the content (or lost to body). It does not do this when the overlay was dismissed by clicking outside, or for hover overlays.
  • Hover overlays also open and close on keyboard focus (focusin / focusout).

Dynamic Positioning

Overlay automatically flips direction when content would go off-screen (dropdown, tooltip and popover types):

  • If align="bottom" but there's no space below, flips to "top" (reported as the resolved alignY)
  • If alignX="left" but content overflows right, adjusts to "right"
  • alignX="center" / alignY="center" centers the content on the trigger. Since 2.9, if the centered content overflows one edge, it aligns to the trigger edge on that side: overflowing on the right right-aligns it to the trigger (likewise for bottom, left and top). This pulls it back on-screen. Before 2.9 it picked the opposite side and pushed the content further off-screen.

How Positioning Works

  1. Content mounts in portal — contentRef callback fires, signals ready
  2. getBoundingClientRect() — Measures trigger and content dimensions
  3. Viewport check — Tests if content fits in preferred direction (fitsTop, fitsBottom, fitsLeft, fitsRight)
  4. Auto-flip — If preferred direction doesn't fit, selects the best alternative
  5. Offset application — Adds offsetX/offsetY margins
  6. Style assignment — Sets position, top, left, right, bottom directly on the content element

Absolute vs Fixed Positioning

  • position: 'fixed' (default): Content positioned relative to the viewport
  • position: 'absolute': Content positioned relative to its offsetParent. The system automatically subtracts the offsetParent's viewport rect to compute correct placement.

When type="modal" and the content has mounted:

  • Focus moves to the first focusable element inside the content (or to the content itself if nothing is focusable), and Tab / Shift+Tab wrap inside it. Focus returns to the previously focused element on close.
  • The focusable set covers links, enabled form controls, [contenteditable], video[controls], audio[controls], summary and [tabindex] (not -1). It skips input[type="hidden"], aria-disabled="true", and anything inside a [hidden] or [inert] subtree. A MutationObserver keeps the set current.
  • With nested modals, only the topmost trap handles Tab (2.9). Before, the outer trap pulled focus back to its own first control.
  • document.body.style.overflow = 'hidden' prevents background scrolling. The lock is reference-counted across open modals, and the original value is restored when the last one closes.

Performance

  • Position recalculation is throttled by throttleDelay (default: 200ms)
  • Scroll and resize listeners use { passive: true } for better scrolling performance
  • useLayoutEffect + requestAnimationFrame — positions immediately, then re-measures after browser reflow
  • Throttled callbacks use the "latest ref" pattern to access current state without stale closures

Nested Overlays

Child overlays automatically block their parent from closing while they are open, so clicks and hovers inside the nested content don't close the parent. Escape closes one layer at a time. A hover parent keeps tracking the pointer while it is blocked: if the pointer leaves while a nested overlay is open, the parent closes once the nested one closes (2.9).

<Overlay trigger={<button>Main Menu</button>}>
  {(props) => (
    <div ref={props.ref}>
      <div>Item 1</div>
      <Overlay trigger={<div>Submenu</div>} align="right">
        {(subProps) => (
          <div ref={subProps.ref}>
            <div>Sub Item 1</div>
            <div>Sub Item 2</div>
          </div>
        )}
      </Overlay>
    </div>
  )}
</Overlay>

useOverlay Hook

For full control without the Overlay component:

import { useOverlay } from '@vitus-labs/elements'

function CustomDropdown() {
  const {
    active,
    triggerRef,
    contentRef,  // callback ref!
    showContent,
    hideContent,
    Provider,
    ...ctx
  } = useOverlay({
    openOn: 'click',
    closeOnEsc: true,
  })

  return (
    <>
      <button ref={triggerRef} onClick={showContent}>
        Toggle
      </button>
      {active && (
        <Portal>
          <Provider {...ctx}>
            <div ref={contentRef}>Content</div>
          </Provider>
        </Portal>
      )}
    </>
  )
}

Important: contentRef is a callback ref — assign it directly as ref={contentRef}.

useOverlay Return Value

PropertyTypeDescription
triggerRefRefObject<HTMLElement>Object ref for trigger element
contentRef(node: HTMLElement) => voidCallback ref for content element
activebooleanCurrent open/close state
alignstringResolved primary direction (after flipping)
alignXstringResolved horizontal alignment (after flipping)
alignYstringResolved vertical alignment (after flipping)
showContent() => voidOpen the overlay
hideContent() => voidClose the overlay
blockedbooleanWhether a nested overlay is blocking close
setBlocked() => voidSignal that a child overlay is active (counted, so several children can block)
setUnblocked() => voidSignal that a child overlay closed
ProviderFCContext provider for nested overlay coordination (also exported as OverlayProvider)

useOverlay takes the same behavior and positioning options as the component (see UseOverlayProps). align is returned as passed; only alignX / alignY reflect flipping.

Event Listeners

These listeners are attached (web only):

EventTargetConditionPurpose
clicktriggerclosed and openOn='click'Open
clickdocumentopen and openOn='click' or a click-based closeOnClose handling (incl. click outside)
keydown (ESC)windowcloseOnEsc && activeClose the topmost overlay on Escape
keydown (Tab)documentmodal openFocus trap
pointerdown / keydowndocument (capture)activeTell an outside-click dismissal apart for focus restoring
resizewindowactiveRecalculate position
scrollwindow + parentContainer (passive)activeRecalculate position; also closes when closeOn='hover'
mouseenter/mouseleave, focusin/focusouttrigger + contentopenOn='hover' or closeOn='hover'Hover interaction with a hoverDelay (100ms) bridge

Since 2.9 a closed click-to-open overlay listens on its trigger only and adds the document click listener only while open. Before, 500 closed overlays added about 280µs to every page click. All listeners are cleaned up on unmount or when the overlay closes.

API Reference

Prop

Type

Edit on GitHub

Last updated on

On this page