Skip to main content

useDropdownListbox

The useDropdownListbox hook provides behaviours for implementing collapsible list boxes, like dropdown select components.

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

  let options = ["Red", "Green", "Blue"]
  let dropdownListbox = Listboxkit.useDropdownListbox(options, ~multiselect=false, ())
PropertiesTypeDescription
highlightedIndexintThe current highlighted index, returns -1 when no option is highlighted.
menuVisibleboolIndicates whether the list box with its options is visible
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.
getDropdownPropsunit => dropdownPropsReturns a record containning the properties to be used in the dropdown element.
getOptionPropsunit => listboxOptionPropsReturns a record containing the properties to be used in the option elements.
hideunit => unitHides the listbox element.
showunit => unitShows the listbox element.

Example

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

@react.component
let make = () => {
  let {
    highlightedIndex,
    menuVisible,
    selectedIndex,
    getOptionProps,
    getDropdownProps,
    getContainerProps,
  } = .useDropdownListbox(options, ~multiSelect=false, ())

  let {role, tabIndex, onKeyDown, onFocus, onBlur} = getContainerProps()

  let dropdownProps = getDropdownProps()
  let selectedOption = selectedIndex === -1 ? "Select a color" : options[selectedIndex]

  <div>
    <div
      role=dropdownProps.role
      tabIndex=dropdownProps.tabIndex
      onClick=dropdownProps.onClick
      className="dropdown-button"
      onKeyDown=dropdownProps.onKeyDown>
      {selectedOption->React.string}
      <div className="dropdown">
        <ul className="listbox" role tabIndex onKeyDown onFocus onBlur hidden={!menuVisible}>
          {options
          ->Js.Array2.mapi((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>
          })
          ->React.array}
        </ul>
      </div>
    </div>
  </div>
}