Skip to main content

useListbox

The useListbox hook provides the basic behaviours for implementing listbox components.

Given a list of options, this hook returns a listbox record containing the listbox current state and functions to bind event handlers and aria attributes.

  let options = ["Red", "Green", "Blue"]
  let listbox = Listboxkit.useListbox(options, ~multiselect=true, ())
PropertiesTypeDescription
highlightedIndexintThe current highlighted index, returns -1 when no option is highlighted.
selectedIndexintThe current selected index, returns -1 when no option is selected.
selectedIndexesarray<int>The current selected indexes, in case is a multiselect is true.
getContainerPropsunit => listboxContainerPropsReturns a record containing the properties to be used in the container element.
getOptionPropsunit => listboxOptionPropsReturns a record containing the properties to be used in the option elements.

Example

  • Red
  • Green
  • Blue
let options = ["Red", "Green", "Blue"]

@react.component
let make = () => {
  let {highlightedIndex, getOptionProps, getContainerProps} = Listboxkit.useListbox(
    options,
    ~multiSelect=false,
    (),
  )

  let {role, tabIndex, onKeyDown, onFocus, onBlur} = getContainerProps()
  let listOption = (option, index) => {
    let {ariaSelected, onClick, role} = getOptionProps(index)
    let highlighted = highlightedIndex == index
    let className = ["listbox-option", highlighted ? "highlighted" : ""]->Js.Array2.joinWith(" ")

    <li className key=option onClick onKeyDown role ariaSelected> {option->React.string} </li>
  }

  <ul className="listbox" role tabIndex onKeyDown onFocus onBlur>
    {options->Js.Array2.mapi(listOption)->React.array}
  </ul>
}