🚀 DAY 5 OF LAUNCH WEEK:Introducing Webhook Events for Alert Changes.Learn more
Socket
Book a DemoInstallSign in
Socket

@bento/listbox

Package Overview
Dependencies
Maintainers
3
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bento/listbox

Listbox component

latest
Source
npmnpm
Version
0.1.3
Version published
Maintainers
3
Created
Source

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:

  • [data-empty] - Applied when the listbox contains no items
  • [data-focused] - Applied when the listbox is focused
  • [data-focus-visible] - Applied when the listbox has keyboard focus
  • [data-layout="stack"] - The layout type (currently only "stack" supported)
  • [data-orientation="vertical|horizontal"] - The primary orientation
  • [data-selection-mode="none|single|multiple"] - The selection mode
  • [data-selection-behavior="toggle|replace"] - How selection behaves
  • [data-allows-tab-navigation] - Whether tab navigation is enabled
  • [data-focus-wrap] - Whether focus wraps around the collection

ListBoxItem Attributes

Individual ListBoxItem components expose these data attributes:

  • [data-selected] - Applied when the item is selected
  • [data-disabled] - Applied when the item is disabled
  • [data-hovered] - Applied when the item is being hovered
  • [data-focused] - Applied when the item is focused
  • [data-focus-visible] - Applied when the item has keyboard focus
  • [data-pressed] - Applied when the item is being pressed
  • [data-level] - The nesting level (useful for indentation)
  • [data-selection-mode] - Inherited selection mode
  • [data-selection-behavior] - Inherited selection behavior
  • [data-text-value] - The computed text value for the item

ListBoxSection Attributes

The ListBoxSection component exposes:

  • [data-level] - The nesting level of the section

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;
}

Keywords

a11y

FAQs

Package last updated on 06 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts