npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bento/listbox

v0.2.1

Published

Listbox component

Readme

ListBox

The @bento/listbox package provides a flexible, accessible listbox primitive that supports both controlled and uncontrolled selection modes. Built on React Aria for interaction fidelity and designed for composition within higher-level components like Select, Combobox, and Menu.

Installation

npm install --save @bento/listbox

Component Structure

The @bento/listbox package exports five main components:

  • ListBox: The main container component that manages selection state, keyboard navigation, and accessibility
  • ListBoxItem: Individual selectable items within the listbox
  • ListBoxSection: Optional grouping component for organizing options into sections
  • Header: Accessible heading for a ListBoxSection, forwards props and refs for full styling control
  • Collection: Utility for rendering nested dynamic data inside a ListBoxSection (or other collection-aware context).

Props

The following properties are available on the ListBox component:

Static Items

/* v8 ignore next */
import React from 'react';
import { ListBox, ListBoxItem } from '@bento/listbox';
import style from './listbox.module.css';

/**
 * Example component demonstrating basic ListBox usage.
 *
 * @param {any} args - The component props.
 * @returns {JSX.Element} The rendered ListBox with static items.
 * @public
 */
export function BasicListBoxExample(args: any) {
  return (
    <ListBox {...args} className={style.listbox}>
      <ListBoxItem>Chicken Teriyaki</ListBoxItem>
      <ListBoxItem>Salmon Bento</ListBoxItem>
      <ListBoxItem>Beef Bowl</ListBoxItem>
    </ListBox>
  );
}

Sections

Use ListBoxSection to group related options. Use Header inside a ListBoxSection to render an accessible heading for the group. It automatically links the heading to the section via aria-labelledby.

The <Header> component accepts standard DOM props and a slot prop for Bento’s slot system, enabling fine-grained overrides in composite components.

/* v8 ignore next */
import React from 'react';
import { ListBox, ListBoxItem, ListBoxSection, Header } from '@bento/listbox';
import style from './listbox.module.css';

/**
 * Example component demonstrating ListBox with static sections.
 *
 * @param {any} args - The component props.
 * @returns {JSX.Element} The rendered ListBox with sectioned items.
 * @public
 */
export function SectionsExample(args: any) {
  return (
    <ListBox {...args} className={style.listbox}>
      <ListBoxSection>
        <Header>Main Dishes</Header>
        <ListBoxItem>Chicken Teriyaki</ListBoxItem>
        <ListBoxItem>Salmon Bento</ListBoxItem>
      </ListBoxSection>
      <ListBoxSection>
        <Header>Side Dishes</Header>
        <ListBoxItem>Pickled Vegetables</ListBoxItem>
        <ListBoxItem>Edamame</ListBoxItem>
      </ListBoxSection>
    </ListBox>
  );
}

Dynamic Collections

For dynamic data, use the items prop with a render function. The ListBox component follows different patterns depending on how it's used:

When items prop is provided

When you provide an items prop, the children function receives individual items for React Aria compatibility:

/* v8 ignore next */
import React from 'react';
import { ListBox, ListBoxItem } from '@bento/listbox';
import style from './listbox.module.css';

/**
 * Example component demonstrating ListBox with dynamic collections.
 *
 * @param {any} args - The component props including items array.
 * @returns {JSX.Element} The rendered ListBox with dynamic items.
 * @public
 */
export function DynamicCollectionExample({ items, ...args }: any) {
  return (
    <ListBox {...args} className={style.listbox} items={items}>
      {(item: any) => (
        <ListBoxItem key={item.id} textValue={item.name}>
          {item.name}
        </ListBoxItem>
      )}
    </ListBox>
  );
}

In this pattern, children is called for each item in the items array, receiving the individual item data to render ListBoxItem components.

When no items prop is provided

When you don't provide an items prop but use children as a function, it follows Bento's render prop pattern and receives an object with render props:

<ListBox aria-label="Custom ListBox">
  {({ isEmpty, isFocused, state, items }) => (
    isEmpty ? (
      <div>No items available</div>
    ) : (
      // Render items normally using static children or other logic
      <ListBoxItem>Static Item</ListBoxItem>
    )
  )}
</ListBox>

This pattern provides access to the ListBox's state, focus status, and other render props following Bento's consistent render prop API.

Nested Collections with Sections

You can also render nested data inside a section using the exported Collection component:

/* v8 ignore next */
import React from 'react';
import { ListBox, ListBoxItem } from '@bento/listbox';
import style from './listbox.module.css';

/**
 * Example component demonstrating ListBox with dynamic collections.
 *
 * @param {any} args - The component props including items array.
 * @returns {JSX.Element} The rendered ListBox with dynamic items.
 * @public
 */
export function DynamicCollectionExample({ items, ...args }: any) {
  return (
    <ListBox {...args} className={style.listbox} items={items}>
      {(item: any) => (
        <ListBoxItem key={item.id} textValue={item.name}>
          {item.name}
        </ListBoxItem>
      )}
    </ListBox>
  );
}

Customization

The ListBox components provide extensive customization options through data attributes, slots, render props, and standard CSS styling. This section covers all available approaches to customize the appearance and behavior.

Styling with Data Attributes

All ListBox components expose their internal state through data attributes, enabling CSS-based styling without JavaScript. This follows Bento's design philosophy of returning styling control to CSS.

ListBox Container Attributes

The main ListBox component exposes these data attributes:

| Attribute | Description | Example Values | | ---------------------------- | ------------------------------------------------- | ----------------------------- | | data-empty | Applied when the listbox contains no items | "true" | | data-focused | Applied when the listbox is focused | "true" | | data-focus-visible | Applied when the listbox has keyboard focus | "true" | | data-layout | The layout type | "stack" | | data-orientation | The primary orientation | "vertical" / "horizontal" | | data-selection-mode | The selection mode | "none" / "single" / "multiple"| | data-selection-behavior | How selection behaves | "toggle" / "replace" | | data-allows-tab-navigation | Whether tab navigation is enabled | "true" | | data-focus-wrap | Whether focus wraps around the collection | "true" |

ListBoxItem Attributes

Individual ListBoxItem components expose these data attributes:

| Attribute | Description | Example Values | | ------------------------ | ------------------------------------------ | ----------------------------- | | data-selected | Applied when the item is selected | "true" | | data-disabled | Applied when the item is disabled | "true" | | data-hovered | Applied when the item is being hovered | "true" | | data-focused | Applied when the item is focused | "true" | | data-focus-visible | Applied when the item has keyboard focus | "true" | | data-pressed | Applied when the item is being pressed | "true" | | data-level | The nesting level (useful for indentation) | "0" / "1" / "2" | | data-selection-mode | Inherited selection mode | "none" / "single" / "multiple"| | data-selection-behavior| Inherited selection behavior | "toggle" / "replace" | | data-text-value | The computed text value for the item | "Item text" |

ListBoxSection Attributes

The ListBoxSection component exposes:

| Attribute | Description | Example Values | | ------------ | -------------------------------- | --------------- | | data-level | The nesting level of the section | "0" / "1" / "2" |

CSS Styling Examples

/* Basic item styling */
[role="option"] {
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.15s ease-in-out;
  cursor: pointer;
}

/* Selected items */
[role="option"][data-selected] {
  background: Highlight;
  color: HighlightText;
}

/* Hovered items */
[role="option"][data-hovered] {
  background: color-mix(in srgb, Highlight 10%, transparent);
}

/* Disabled items */
[role="option"][data-disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Focused items (keyboard navigation) */
[role="option"][data-focus-visible] {
  outline: 2px solid Highlight;
  outline-offset: -2px;
}

/* Combined states */
[role="option"][data-selected][data-hovered] {
  background: color-mix(in srgb, Highlight 90%, white);
}

/* Empty state styling */
.listbox[data-empty] {
  min-height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #64748b;
}

/* Section headers */
.section-header {
  font-weight: 600;
  font-size: 0.875rem;
  color: #64748b;
  padding: 6px 12px;
  margin-bottom: 4px;
}

Slots System

The components use Bento's @bento/slots package for fine-grained component overrides. Slots allow you to replace or wrap specific parts of the component tree with custom implementations.

Basic Slot Usage

/* v8 ignore next */
import React from 'react';
import { ListBox, ListBoxItem, ListBoxSection, Header, Collection } from '@bento/listbox';
import { useProps } from '@bento/use-props';
import style from './listbox.module.css';

//
// Slot namespace layout:
//
// ```
// bento-list                 (ListBox)
// ├── main-dishes            (ListBoxSection)
// │   ├── header             (Header)
// │   ├── chicken-teriyaki   (ListBoxItem)
// │   └── salmon-bento       (ListBoxItem)
// └── side-dishes            (ListBoxSection)
//     ├── header             (Header)
//     ├── pickled-vegetables (ListBoxItem)
//     └── edamame            (ListBoxItem)
// ```
//
// This example demonstrates several slot override patterns:
// 1. `side-dishes.header` – Custom header component with enhanced styling
// 2. `side-dishes.pickled-vegetables` – Override specific item in specific section
// 3. `main-dishes` – Override entire section styling
//

/**
 * Example component demonstrating ListBox with dynamic sections and slot overrides.
 *
 * @param {any} args - The component props including categories and slots.
 * @returns {JSX.Element} The rendered ListBox with slotted dynamic sections.
 * @public
 */
export function SlotsDynamicSectionsExample({ categories, ...args }: any) {
  const {
    items: argItems,
    slots: argSlots = {},
    ...rest
  } = args as {
    items?: Iterable<unknown>;
    slots?: Record<string, any>;
  } & Record<string, unknown>;

  const { apply } = useProps(rest);

  //
  // Default slot overrides for demo - these show different override patterns
  //
  const demoSlots: Record<string, any> = {
    //
    // Override a header in a specific section with custom styling
    //
    'side-dishes.header': ({ props, original }: { props: Record<string, any>; original: React.ReactNode }) => (
      <Header {...props}>🥢 {original}</Header>
    ),

    //
    // Override another specific item with custom content
    //
    'side-dishes.pickled-vegetables': ({ original }: { original: React.ReactNode }) => (
      <div style={{ backgroundColor: '#4ade80', color: 'white', padding: '2px 6px', borderRadius: '4px' }}>
        🥒 {original} (Traditional)
      </div>
    ),

    //
    // Override an entire section with custom wrapper
    //
    'main-dishes': ({ original }: { original: React.ReactNode }) => (
      <div style={{ border: '2px dashed #f59e0b', padding: '8px', borderRadius: '6px' }}>{original}</div>
    )
  };

  //
  // Merge provided slots with demo slots (provided slots take precedence)
  //
  const mergedSlots = { ...demoSlots, ...argSlots };

  return (
    <ListBox
      {...apply({ className: style.listbox })}
      // Only set items if caller didn't already supply one
      items={argItems ?? categories}
      slot="bento-list"
      slots={mergedSlots}
    >
      {(category: any) => (
        <ListBoxSection key={category.id} slot={category.id}>
          <Header slot="header">{category.name}</Header>
          <Collection items={category.items}>
            {(item: { id: string; name: string }) => (
              <ListBoxItem key={item.id} textValue={item.name} slot={item.id}>
                {item.name}
              </ListBoxItem>
            )}
          </Collection>
        </ListBoxSection>
      )}
    </ListBox>
  );
}

Advanced Slot Patterns

You can target specific items or sections using hierarchical slot names:

// Override a specific section header
const slots = {
  'my-listbox.fruits.header': ({ original, props }) => (
    <Header {...props}>🍎 {original}</Header>
  ),

  // Override a specific item in a specific section
  'my-listbox.fruits.apple': ({ original }) => (
    <div className="special-item">⭐ {original}</div>
  ),

  // Override an entire section
  'my-listbox.vegetables': ({ original }) => (
    <div className="veggie-section">{original}</div>
  )
};

<ListBox slot="my-listbox" slots={slots}>
  <ListBoxSection slot="fruits">
    <Header slot="header">Fruits</Header>
    <ListBoxItem slot="apple">Apple</ListBoxItem>
    <ListBoxItem slot="orange">Orange</ListBoxItem>
  </ListBoxSection>
  <ListBoxSection slot="vegetables">
    <Header slot="header">Vegetables</Header>
    <ListBoxItem slot="carrot">Carrot</ListBoxItem>
  </ListBoxSection>
</ListBox>

Render Props

The ListBoxItem component supports render prop patterns for dynamic content based on interaction state:

// ListBoxItem render prop with interaction state
<ListBoxItem>
  {({ isSelected, isHovered, isDisabled }) => (
    <div className={`item ${isSelected ? 'selected' : ''}`}>
      {isHovered && '👆 '}
      My Item
      {isSelected && ' ✓'}
    </div>
  )}
</ListBoxItem>

For ListBox-level render props, use the renderEmptyState prop to customize empty state display:

<ListBox
  items={items}
  renderEmptyState={({ isEmpty, isFocused, state, items }) => (
    <div className="empty-state">
      {isFocused ? 'No items found (focused)' : 'No items available'}
    </div>
  )}
>
  {(item: any) => (
    <ListBoxItem key={item.id} textValue={item.name}>
      {item.name}
    </ListBoxItem>
  )}
</ListBox>

Empty State Customization

Customize the appearance when no items are present:

<ListBox
  renderEmptyState={({ isEmpty, isFocused }) => (
    <div className="empty-state">
      <span>📭</span>
      <p>No items to display</p>
      {isFocused && <p>Start typing to search...</p>}
    </div>
  )}
>
  {/* Items when present */}
</ListBox>

Accessibility Customization

All components support standard ARIA attributes for enhanced accessibility:

<ListBox
  aria-label="Food menu"
  aria-describedby="menu-description"
>
  <ListBoxSection aria-label="Main courses">
    <Header>Main Dishes</Header>
    <ListBoxItem aria-label="Chicken teriyaki with rice">
      Chicken Teriyaki
    </ListBoxItem>
  </ListBoxSection>
</ListBox>

CSS-in-JS and Styled Components

The data attributes work seamlessly with CSS-in-JS libraries:

// Styled Components
const StyledListBox = styled.div`
  &[data-focused] {
    box-shadow: 0 0 0 2px blue;
  }

  [role="option"][data-selected] {
    background: ${props => props.theme.primary};
  }
`;

// Emotion
const listboxStyles = css`
  &[data-empty] {
    opacity: 0.5;
  }
`;

Animation and Transitions

Data attributes enable smooth state transitions:

[role="option"] {
  transition: all 0.2s ease-in-out;
  transform: translateY(0);
}

[role="option"][data-hovered] {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

[role="option"][data-pressed] {
  transform: translateY(0);
  transition-duration: 0.1s;
}