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
| Prop | Type | Description |
|---|---|---|
trigger | ReactNode | (props) => ReactNode | Trigger element or render function |
children | ReactNode | (props) => ReactNode | Content to show when open |
DOMLocation | HTMLElement | Portal target (default: document.body) |
triggerRefName | string | Ref prop name for trigger (default: 'ref') |
contentRefName | string | Ref 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.
| Prop | Type | Default | Description |
|---|---|---|---|
isOpen | boolean | false | Initial open state |
openOn | 'click' | 'hover' | 'manual' | 'click' | How to open |
closeOn | 'click' | 'clickOnTrigger' | 'clickOutsideContent' | 'hover' | 'manual' | 'click' | How to close |
closeOnEsc | boolean | true | Close on ESC key (only the topmost open overlay closes) |
hoverDelay | number | 100 | Delay (ms) before hiding on hover leave; bridges the gap between trigger and content |
disabled | boolean | — | Closes the overlay and blocks it from opening |
onOpen | () => void | — | Called on open |
onClose | () => void | — | Called on close |
Positioning
| Prop | Type | Default | Description |
|---|---|---|---|
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 |
offsetX | number | 0 | Horizontal margin |
offsetY | number | 0 | Vertical margin |
throttleDelay | number | 200 | Position recalculation throttle (ms) |
parentContainer | HTMLElement | 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>| Prop | Type | Description |
|---|---|---|
active | boolean | Whether content is visible |
showContent | () => void | Open the overlay |
hideContent | () => void | Close 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>| Prop | Type | Description |
|---|---|---|
active | boolean | Whether content is visible |
align | string | The align prop as passed |
alignX | string | Resolved horizontal alignment (after any flip) |
alignY | string | Resolved vertical alignment (after any flip) |
showContent | () => void | Open |
hideContent | () => void | Close |
Positioning Types
Dropdown
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>Modal
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) andaria-controlswhile open. Tooltip triggers getaria-describedbyinstead. - The content gets an
id, plusrole="dialog"+aria-modalfor modals androle="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 resolvedalignY) - 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
- Content mounts in portal —
contentRefcallback fires, signals ready getBoundingClientRect()— Measures trigger and content dimensions- Viewport check — Tests if content fits in preferred direction (
fitsTop,fitsBottom,fitsLeft,fitsRight) - Auto-flip — If preferred direction doesn't fit, selects the best alternative
- Offset application — Adds
offsetX/offsetYmargins - Style assignment — Sets
position,top,left,right,bottomdirectly on the content element
Absolute vs Fixed Positioning
position: 'fixed'(default): Content positioned relative to the viewportposition: 'absolute': Content positioned relative to itsoffsetParent. The system automatically subtracts theoffsetParent's viewport rect to compute correct placement.
Modal Focus Trap and Scroll Lock
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],summaryand[tabindex](not-1). It skipsinput[type="hidden"],aria-disabled="true", and anything inside a[hidden]or[inert]subtree. AMutationObserverkeeps 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
| Property | Type | Description |
|---|---|---|
triggerRef | RefObject<HTMLElement> | Object ref for trigger element |
contentRef | (node: HTMLElement) => void | Callback ref for content element |
active | boolean | Current open/close state |
align | string | Resolved primary direction (after flipping) |
alignX | string | Resolved horizontal alignment (after flipping) |
alignY | string | Resolved vertical alignment (after flipping) |
showContent | () => void | Open the overlay |
hideContent | () => void | Close the overlay |
blocked | boolean | Whether a nested overlay is blocking close |
setBlocked | () => void | Signal that a child overlay is active (counted, so several children can block) |
setUnblocked | () => void | Signal that a child overlay closed |
Provider | FC | Context 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):
| Event | Target | Condition | Purpose |
|---|---|---|---|
click | trigger | closed and openOn='click' | Open |
click | document | open and openOn='click' or a click-based closeOn | Close handling (incl. click outside) |
keydown (ESC) | window | closeOnEsc && active | Close the topmost overlay on Escape |
keydown (Tab) | document | modal open | Focus trap |
pointerdown / keydown | document (capture) | active | Tell an outside-click dismissal apart for focus restoring |
resize | window | active | Recalculate position |
scroll | window + parentContainer (passive) | active | Recalculate position; also closes when closeOn='hover' |
mouseenter/mouseleave, focusin/focusout | trigger + content | openOn='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
Last updated on