useListbox
useListbox provides the positioning, open state, and ARIA props for a listbox
popover. Use it with ListboxContext and useOption when building a custom
select or another listbox-based control. For a complete trigger and keyboard
interaction model, use useSelect instead.
The hook returns props for the listbox and controls for opening and closing it.
Provide the returned context from useSelect when rendering options; useListbox
alone is intended for consumers that manage selection and context themselves.
import { useListbox } from '@volvo-cars/react-headless';
function Listbox() { const { anchorProps, listboxProps, isOpen, showPopover, hidePopover } = useListbox({ placement: 'bottom-start', matchTriggerWidth: true, });
return ( <> <button type="button" {...anchorProps} onClick={showPopover}> Open options </button> {isOpen ? ( <div {...listboxProps}> {/* Render options here. */} <button type="button" onClick={hidePopover}> Close </button> </div> ) : null} </> );}Positioning
Section titled “Positioning”The listbox is anchored below the trigger by default. Set placement and
offset to control its position and distance from the trigger. Set
matchTriggerWidth to make the listbox at least as wide as the trigger, and
use minWidth to set an explicit minimum width.
Set anchored to false when CSS positions the listbox, for example when it
becomes a bottom sheet on small screens.
Selection mode
Section titled “Selection mode”Set mode to 'multiple' to mark the listbox as multiselectable. The default
mode is 'single'.
Options
Section titled “Options”mode:'single'or'multiple'(default:'single')placement: the popover placement (default:'bottom-start')offset: distance from the trigger in pixels (default:8)matchTriggerWidth: matches the listbox width to the trigger (default:false)minWidth: minimum listbox widthanchored: whether the listbox is positioned next to the trigger (default:true)onToggle: callback for the popoverToggleEvent
Returns
Section titled “Returns”isOpen: whether the listbox is openshowPopover: opens the listboxhidePopover: closes the listboxtogglePopover: toggles the listboxanchorProps: props to spread on the trigger or anchor elementlistboxProps: props to spread on the listbox elementfloatingRef: ref captured by the listbox for active-option scrolling