DEV Community


React listbox component

tmikeschu profile image Mike Schutte ・1 min read

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 and ListboxOption 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 Context, and keys, I was able to implement a lovely compound component API.

  { => (
    <ListboxOption key={}>
      <Item {...item} />
Enter fullscreen mode Exit fullscreen mode

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 ✌️

Discussion (0)

Editor guide