Skip to content

useListbox

Edit on GitHub
@volvo-cars/react-headless v0.27.2

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}
</>
);
}

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.

Set mode to 'multiple' to mark the listbox as multiselectable. The default mode is 'single'.

  • 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 width
  • anchored: whether the listbox is positioned next to the trigger (default: true)
  • onToggle: callback for the popover ToggleEvent
  • isOpen: whether the listbox is open
  • showPopover: opens the listbox
  • hidePopover: closes the listbox
  • togglePopover: toggles the listbox
  • anchorProps: props to spread on the trigger or anchor element
  • listboxProps: props to spread on the listbox element
  • floatingRef: ref captured by the listbox for active-option scrolling