usePopover
usePopover
is a wrapper around the Floating UI library. It provides an API for positioning floating elements next to reference elements. This can be useful for creating tooltips, dropdowns, popovers, and other floating elements.
Usage
Simple Tooltip component example built using usePopover
.
For a minimal example, we can implement a floating element using two properties returned by the usePopover
hook.
refs
- An object that contains asetReference
andsetFloating
function. These functions should be bound to the element that the floating element will be positioned relative to and the floating element itself, respectively.style
- An object containing the position styles for your floating element.
By binding these properties to the appropriate elements, we can create any floating element - in this case, we have a Tooltip that displays when the reference element is hovered.
import * as React from 'react';
import { usePopover } from '@storefront-ui/react';
interface TooltipProps {
children?: React.ReactNode;
text?: string;
}
function Tooltip({ children, text }: TooltipProps) {
const [isOpen, setOpen] = React.useState(false);
const { refs, style } = usePopover({ isOpen });
return (
<span ref={refs.setReference} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
{children}
{isOpen && (
<div ref={refs.setFloating} style={style} className="p-2 rounded bg-black text-white">
{text}
</div>
)}
</span>
);
}