useFloating
Lightweight, zero-dependency positioning for tooltips, popovers, dropdowns, and similar UI. Computes floatingStyles to place a floating element on a chosen side / alignment relative to a reference element, with optional flip and shift to keep it in the viewport. Recomputes on scroll and resize while open.
For more advanced needs (auto-update on any layout shift, virtual elements, middleware composition), pair with @floating-ui/dom.
import { useRef, useState } from 'react'
import { useFloating } from '@wire-ui/react'
function Tooltip({ children, label }: { children: React.ReactNode; label: string }) {
const [open, setOpen] = useState(false)
const referenceRef = useRef<HTMLButtonElement>(null)
const floatingRef = useRef<HTMLDivElement>(null)
const { floatingStyles, side } = useFloating(referenceRef, floatingRef, {
open,
side: 'top',
offset: 6,
})
return (
<>
<button
ref={referenceRef}
onMouseEnter={() => setOpen(true)}
onMouseLeave={() => setOpen(false)}
>
{children}
</button>
{open && (
<div ref={floatingRef} style={floatingStyles} data-side={side} role="tooltip">
{label}
</div>
)}
</>
)
}Parameters
| Param | Type | Description |
|---|---|---|
referenceRef | RefObject<HTMLElement | null> | Element the floating element is positioned against. |
floatingRef | RefObject<HTMLElement | null> | The floating element itself. |
options | UseFloatingOptions | See below. |
Options
| Option | Type | Default | Description |
|---|---|---|---|
open | boolean | true | Positioning only runs when true. |
side | 'top' | 'right' | 'bottom' | 'left' | 'bottom' | Preferred side. |
align | 'start' | 'center' | 'end' | 'center' | Alignment along the chosen side. |
offset | number | 8 | Gap in pixels between reference and floating. |
strategy | 'absolute' | 'fixed' | 'absolute' | fixed is safer inside transformed / clipping ancestors. |
flip | boolean | true | Flip to the opposite side when there isn’t room. |
shift | boolean | true | Shift along the main axis to stay in the viewport. |
Returns
| Key | Type | Description |
|---|---|---|
x | number | Horizontal coordinate. |
y | number | Vertical coordinate. |
side | FloatingSide | Final side (may flip from the requested side). |
align | FloatingAlign | Final alignment. |
strategy | FloatingStrategy | The positioning strategy used. |
floatingStyles | CSSProperties | Styles to apply to the floating element. |
update | () => void | Recompute position imperatively. |
Last updated on