Popover and Floating UI in React: Positioning, Arrow, Flip
Build popovers, tooltips, and dropdowns in React that actually stay on screen - a practical guide to Floating UI v2 positioning, arrows, and flip middleware.
Why Positioning Floaters Is Harder Than It Looks
You've done it. You wired up position: absolute, set top: calc(100% + 8px), and called it a day. Works fine - until the trigger is near the bottom of the viewport, the tooltip clips off-screen, and no one notices until a designer screenshots it. That's the trap.
Floating elements - popovers, dropdowns, tooltips, context menus, date pickers - all share the same problem: they need to stay inside the viewport no matter where their anchor is. The anchor can be near any edge. The page might be scrolled, zoomed, or inside an iframe. Raw CSS doesn't know any of that.
This is why Floating UI (previously Popper.js v3, released as Floating UI v1 in 2022) exists. It's a low-level library that computes the x and y coords for a floating element relative to its reference, then applies middleware like flip, shift, and arrow to keep it inside whatever boundary you set. As of v2.x it's framework-agnostic core with a first-class React package, @floating-ui/react. No opinions about markup. No forced portals. Just math.
Honestly, it's the library I wish existed in 2019 when I was wrestling Popper v1 into a design system that had to support right-to-left layouts, overflow: hidden scroll containers, and IE11 all at once. Floating UI gets those cases right by default.
Quick aside: if you want production-ready popovers without wiring everything up yourself, browse components at Empire UI - several interaction patterns already ship with Floating UI baked in.
Installing Floating UI and the React Adapter
Two packages. That's it. The core package handles the math; the React adapter gives you hooks.
npm install @floating-ui/react
# or
pnpm add @floating-ui/reactThe React package re-exports everything from @floating-ui/dom and @floating-ui/core, so you don't need to install those separately. Worth noting: @floating-ui/react reached v0.26 in late 2025 and its API has been stable enough to use in production since around v0.19. The hook-based API we're using here works from v0.19 onward.
One more thing - if you're using Next.js with the App Router, you don't need to do anything special. Floating UI is a client-side library, so the components using it need 'use client' at the top, but there are no SSR issues because the positioning only runs after mount.
The Core Hook: useFloating
useFloating is the main entry point. It returns refs you attach to your anchor and floating elements, plus the computed x, y coordinates and a strategy ('absolute' or 'fixed'). Here's the minimal setup:
import { useFloating } from '@floating-ui/react';
function BasicTooltip() {
const { refs, floatingStyles } = useFloating();
return (
<>
<button ref={refs.setReference}>Hover me</button>
<div ref={refs.setFloating} style={floatingStyles}>
Tooltip content
</div>
</>
);
}That gives you a floating div positioned directly below the button. No flip, no boundary detection, no arrow - just raw placement. In practice you'll always add middleware, but understanding this baseline makes the rest make sense.
The floatingStyles object is { position: 'absolute', top: y, left: x, ... }. You spread it onto the floating element's style prop. Floating UI never writes to the DOM directly - it hands you numbers and you apply them. That's the right call for React.
By default, placement is 'bottom'. You can pass { placement: 'top' } or any of the 12 placement values (top-start, right-end, etc.) as an option to useFloating. The middleware pipeline then adjusts from that starting placement.
Middleware: flip, shift, offset, and arrow
Middleware is where Floating UI earns its keep. Each piece runs in order and can mutate the final position. The four you'll use on almost every floating element:
import {
useFloating,
autoUpdate,
offset,
flip,
shift,
arrow,
} from '@floating-ui/react';
import { useRef } from 'react';
function Popover({ children, content }: { children: React.ReactNode; content: string }) {
const arrowRef = useRef<HTMLDivElement>(null);
const { refs, floatingStyles, middlewareData, placement } = useFloating({
placement: 'top',
// re-run positioning on scroll / resize / anchor size change
whileElementsMounted: autoUpdate,
middleware: [
// 8px gap between anchor and floating element
offset(8),
// flip to opposite side if not enough room
flip(),
// keep it inside the viewport by shifting along the axis
shift({ padding: 8 }),
// compute where the arrow tip should point
arrow({ element: arrowRef }),
],
});
const arrowData = middlewareData.arrow;
const side = placement.split('-')[0];
const staticSide = { top: 'bottom', right: 'left', bottom: 'top', left: 'right' }[side]!;
return (
<>
<span ref={refs.setReference}>{children}</span>
<div
ref={refs.setFloating}
style={floatingStyles}
className="bg-gray-900 text-white text-sm px-3 py-2 rounded-lg shadow-xl"
>
{content}
{/* Arrow element */}
<div
ref={arrowRef}
style={{
position: 'absolute',
left: arrowData?.x != null ? `${arrowData.x}px` : '',
top: arrowData?.y != null ? `${arrowData.y}px` : '',
[staticSide]: '-4px',
width: 8,
height: 8,
background: 'inherit',
transform: 'rotate(45deg)',
}}
/>
</div>
</>
);
}flip() by default checks the opposite side first, then the adjacent sides, to find a placement with enough room. You can customise the fallback order via { fallbackPlacements: ['bottom', 'right'] }. shift() is your safety net - if even after flipping there's not enough room, it slides the popover along the cross-axis so at least it's visible. The padding: 8 keeps it 8px from viewport edges.
offset(8) is the gap between the anchor element and the floating element. That's a real 8px gap, not a margin on the element - it's factored into the coordinate calculation so the arrow math stays correct.
The arrow computation gives you arrowData.x and arrowData.y - only one is defined at a time depending on placement axis. staticSide is the CSS property you point toward the anchor. The rotate(45deg) trick on a square div is the oldest CSS arrow technique in the book, and it still works better than SVG for this because it inherits background color automatically.
Look, the arrow code is a bit verbose the first time you write it. Extract it into an <Arrow> component and you'll never think about it again. That's exactly what Empire UI's glassmorphism components do internally - the positioning primitives are abstracted so you just drop in a <Tooltip> or <Popover> and move on.
Building a Full Popover with Open/Close State
A tooltip is display-only. A popover is interactive - it opens on click, traps focus, and closes on outside click or Escape. Floating UI v0.26 ships useInteractions, useClick, useDismiss, and useFocus hooks that handle all of that without extra libraries.
import {
useFloating,
autoUpdate,
offset,
flip,
shift,
useClick,
useDismiss,
useRole,
useInteractions,
FloatingFocusManager,
} from '@floating-ui/react';
import { useState } from 'react';
export function Popover({ trigger, children }: { trigger: React.ReactNode; children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(false);
const { refs, floatingStyles, context } = useFloating({
open: isOpen,
onOpenChange: setIsOpen,
placement: 'bottom-start',
whileElementsMounted: autoUpdate,
middleware: [offset(6), flip(), shift({ padding: 8 })],
});
const click = useClick(context);
const dismiss = useDismiss(context); // closes on outside click + Escape
const role = useRole(context); // sets aria-haspopup + aria-expanded
const { getReferenceProps, getFloatingProps } = useInteractions([click, dismiss, role]);
return (
<>
<button ref={refs.setReference} {...getReferenceProps()}>
{trigger}
</button>
{isOpen && (
<FloatingFocusManager context={context} modal={false}>
<div
ref={refs.setFloating}
style={floatingStyles}
{...getFloatingProps()}
className="bg-white border border-gray-200 rounded-xl shadow-2xl p-4 z-50 min-w-[200px]"
>
{children}
</div>
</FloatingFocusManager>
)}
</>
);
}FloatingFocusManager handles focus trapping when the popover is open and returns focus to the trigger on close. Setting modal={false} keeps it in flow - screen readers can still reach content outside the popover, which is correct for most popover patterns (menus, selects) but wrong for dialogs (use modal={true} there). The distinction matters for WCAG 2.2 compliance.
useRole(context) is doing real work here. It spreads role='dialog', aria-labelledby, and aria-expanded onto the correct elements based on the interaction pattern. You get keyboard and screen reader support for free. That's the part most hand-rolled implementations skip.
In practice, modal={false} + useDismiss gives you the click-outside-to-close behaviour your users expect. No need for a separate overlay div or useEffect cleanup. The library handles the event listener lifecycle internally.
Want this styled for a specific visual language? The glassmorphism generator can spit out the exact CSS for a frosted-glass popover background in under 30 seconds. Swap the bg-white class for your generated glass styles and it's done.
autoUpdate: Keeping Position Correct on Scroll and Resize
This is the part people forget. useFloating computes the position once on mount. If the user scrolls, resizes the window, or the anchor element changes size - the floating element stays where it was. It drifts. autoUpdate fixes that.
import { autoUpdate } from '@floating-ui/react';
// Pass it as whileElementsMounted:
const { refs, floatingStyles } = useFloating({
whileElementsMounted: autoUpdate,
// ...other options
});autoUpdate adds listeners for scroll, resize, and (via ResizeObserver) element size changes. It calls update() on every relevant event. The cleanup runs when whileElementsMounted returns - which happens when either element unmounts. Zero memory leak risk.
One thing worth knowing: autoUpdate listens on the *scroll ancestors* of both the reference and floating elements, not just window. That means it works correctly inside custom scroll containers - the overflow: scroll sidebar, the virtualized list, the nested modal. This was famously the hardest edge case in Popper.js v1.
Styling, Transitions, and Putting It All Together
Floating UI gives you x and y. How you style the popover is entirely your problem. That's a feature. You can use Tailwind, CSS Modules, styled-components, or inline styles - the library doesn't care.
For enter/exit animations, the cleanest approach in React is Framer Motion's AnimatePresence around the conditional render. The floating element's position is already computed before it mounts, so there's no flash-of-wrong-position on entry.
import { AnimatePresence, motion } from 'framer-motion';
// Inside your Popover render:
<AnimatePresence>
{isOpen && (
<FloatingFocusManager context={context} modal={false}>
<motion.div
ref={refs.setFloating}
style={floatingStyles}
{...getFloatingProps()}
initial={{ opacity: 0, scale: 0.95, y: -4 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: -4 }}
transition={{ duration: 0.15, ease: 'easeOut' }}
className="bg-white border border-gray-200 rounded-xl shadow-xl p-4 z-50"
>
{children}
</motion.div>
</FloatingFocusManager>
)}
</AnimatePresence>The y: -4 on initial/exit gives a subtle lift-off effect. Keep the duration at or below 150ms - anything longer feels sluggish for transient UI like popovers. That's not an aesthetic opinion, it's what the WCAG 2.2 animation guidance recommends for UI feedback elements.
For the visual style of the popover itself, check out the box shadow generator to dial in the shadow without guessing. And if your project uses a specific visual language - neobrutalism borders, cyberpunk glow - the Empire UI component library has styled variants ready to drop in, so you're not reinventing the design language for every floating element you build.
FAQ
@floating-ui/dom is the framework-agnostic layer that handles positioning math and DOM measurement. @floating-ui/react wraps it with React hooks like useFloating, useInteractions, and FloatingFocusManager. Install @floating-ui/react and you get both.
Yes, by default flip() tries the opposite placement first, then the adjacent ones. You can override this with fallbackPlacements: ['right', 'left'] to specify exactly which placements to try in order.
Wrap the floating element with FloatingPortal from @floating-ui/react. It renders into document.body by default, which avoids z-index and overflow: hidden stacking issues with parent containers.
No - Radix UI uses Floating UI internally for its Popover, Tooltip, and DropdownMenu primitives since Radix v1.1. So if you're using Radix, you're already getting Floating UI positioning under the hood, just with Radix's component API on top.