I recently posted about a hook that manages the state needed for a list with the listbox
role.
After writing about it and making an isolated code sandbox for it, a thought kept nagging at me.
I shouldn't have to use a hook directly for this. There should be a component for
Listbox
component andListboxOption
that manages that state implicitly.
I don't want to have to manually add the mouseenter
event listener to change the selected item. I want a component to handle that detail for me.
This desire and instinct for implicit compound component state comes from APIs like ReachUI's Tabs.
With the help of React.Children.map
, React Context, and keys, I was able to implement a lovely compound component API.
<Listbox>
{items.map((item) => (
<ListboxOption key={item.id}>
<Item {...item} />
</ListboxOption>
))}
</Listbox>
An item can tell if its selected by way of render props or a useContext
hook. See the details and working example here:
Thanks! Happy coding ✌️
Top comments (0)