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, ())
Properties | Type | Description |
---|---|---|
highlightedIndex | int | The current highlighted index, returns -1 when no option is highlighted. |
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. |
getOptionProps | unit => listboxOptionProps | Returns 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>
}