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, ())
DropdownListbox properties
Properties | Type | Description |
---|---|---|
highlightedIndex | int | The current highlighted index, returns -1 when no option is highlighted. |
menuVisible | bool | Indicates whether the list box with its options is visible |
selectedIndex | int | The current selected index, returns -1 when no option is selected. |
selectedIndexes | array<int> | The current selected indexes, in case is a multiselect is true . |
getContainerProps | unit => listboxContainerProps | Returns a record containing the properties to be used in the container element. |
getDropdownProps | unit => dropdownProps | Returns a record containning the properties to be used in the dropdown element. |
getOptionProps | unit => listboxOptionProps | Returns a record containing the properties to be used in the option elements. |
hide | unit => unit | Hides the listbox element. |
show | unit => unit | Shows 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>
}