React listbox component

tmikeschu

Mike Schutte

Posted on February 2, 2021

React listbox component

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

💖 💪 🙅 🚩
tmikeschu
Mike Schutte

Posted on February 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related