ListBox

A list of options that can allow selection of one or more.

installyarn add @adobe/react-spectrum
added3.0.0
usageimport {ListBox, Item, Section} from '@adobe/react-spectrum'

Example#


<ListBox width="size-2400" aria-label="Alignment">
  <Item>Left</Item>
  <Item>Middle</Item>
  <Item>Right</Item>
</ListBox>
<ListBox width="size-2400" aria-label="Alignment">
  <Item>Left</Item>
  <Item>Middle</Item>
  <Item>Right</Item>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Alignment"
>
  <Item>Left</Item>
  <Item>Middle</Item>
  <Item>Right</Item>
</ListBox>
Left
Middle
Right

Content#


A ListBox displays a list of options, and allows users to select one or more of them. It follows the Collection Components API, accepting both static and dynamic collections. Similar to Picker, ListBox accepts <Item> elements as children, each with a key prop. Basic usage of the ListBox, seen in the example above, shows multiple options populated with a string. Static collections, as in this example, can be used when the full list of options is known ahead of time.

Dynamic collections, as shown below, can be used when the options come from an external data source such as an API call, or update over time. Providing the data in this way allows for ListBox to automatically cache the rendering of each item, which dramatically improves performance.

As seen below, an iterable list of options is passed to the Listbox using the items prop. Each item accepts a key prop, which is passed to the onSelectionChange handler, when present, to identify the selected item. Alternatively, if the item objects contain an id property, as shown in the example below, then this is used automatically and a key prop is not required. See the Events section for more detail on selection. By default, selection is not enabled, however this can be changed using the selectionMode prop. See Selection for more information.

function Example() {
  let options = [
    { id: 1, name: 'Aardvark' },
    { id: 2, name: 'Cat' },
    { id: 3, name: 'Dog' },
    { id: 4, name: 'Kangaroo' },
    { id: 5, name: 'Koala' },
    { id: 6, name: 'Penguin' },
    { id: 7, name: 'Snake' },
    { id: 8, name: 'Turtle' },
    { id: 9, name: 'Wombat' }
  ];
  let [animalId, setAnimalId] = React.useState(null);

  return (
    <>
      <ListBox
        width="size-2400"
        aria-label="Animals"
        items={options}
        selectionMode="single"
        onSelectionChange={setAnimalId}
      >
        {(item) => <Item>{item.name}</Item>}
      </ListBox>
      <p>Animal id: {animalId}</p>
    </>
  );
}
function Example() {
  let options = [
    { id: 1, name: 'Aardvark' },
    { id: 2, name: 'Cat' },
    { id: 3, name: 'Dog' },
    { id: 4, name: 'Kangaroo' },
    { id: 5, name: 'Koala' },
    { id: 6, name: 'Penguin' },
    { id: 7, name: 'Snake' },
    { id: 8, name: 'Turtle' },
    { id: 9, name: 'Wombat' }
  ];
  let [animalId, setAnimalId] = React.useState(null);

  return (
    <>
      <ListBox
        width="size-2400"
        aria-label="Animals"
        items={options}
        selectionMode="single"
        onSelectionChange={setAnimalId}
      >
        {(item) => <Item>{item.name}</Item>}
      </ListBox>
      <p>Animal id: {animalId}</p>
    </>
  );
}
function Example() {
  let options = [
    {
      id: 1,
      name: 'Aardvark'
    },
    {
      id: 2,
      name: 'Cat'
    },
    {
      id: 3,
      name: 'Dog'
    },
    {
      id: 4,
      name: 'Kangaroo'
    },
    {
      id: 5,
      name: 'Koala'
    },
    {
      id: 6,
      name: 'Penguin'
    },
    {
      id: 7,
      name: 'Snake'
    },
    {
      id: 8,
      name: 'Turtle'
    },
    {
      id: 9,
      name: 'Wombat'
    }
  ];
  let [
    animalId,
    setAnimalId
  ] = React.useState(
    null
  );

  return (
    <>
      <ListBox
        width="size-2400"
        aria-label="Animals"
        items={options}
        selectionMode="single"
        onSelectionChange={setAnimalId}
      >
        {(item) => (
          <Item>
            {item.name}
          </Item>
        )}
      </ListBox>
      <p>
        Animal id:{' '}
        {animalId}
      </p>
    </>
  );
}
Aardvark
Cat
Dog
Kangaroo
Koala
Penguin
Snake
Turtle
Wombat

Animal id:

Accessibility#

ListBoxes should be labeled using the aria-label prop. If the ListBox is labeled by a separate element, an aria-labelledby prop must be provided using the id of the labeling element instead.

Internationalization#

To internationalize a ListBox, a localized string should be passed to the children of each Item. For languages that are read right to left (e.g. Hebrew and Arabic), the layout of the ListBox is flipped.

Selection#


ListBox supports no selection, single and multiple selection modes using the selectionMode prop. Setting selected options can be done by using the defaultSelectedKeys or selectedKeys prop. The selected key corresponds to the key of an item. See Events for more details on selection events. Additionally, see the react-stately Selection docs for caveats regarding selection prop typing.

import type {Selection} from '@adobe/react-spectrum';

function Example() {
  let options = [
    { name: 'Koala' },
    { name: 'Kangaroo' },
    { name: 'Platypus' },
    { name: 'Bald Eagle' },
    { name: 'Bison' },
    { name: 'Skunk' }
  ];
  let [selectedKeys, setSelectedKeys] = React.useState<Selection>(
    new Set(['Bison'])
  );

  return (
    <Flex direction="row" gap="size-350">
      <ListBox
        selectionMode="multiple"
        aria-label="Pick an animal"
        items={options}
        defaultSelectedKeys={['Bison', 'Koala']}
        width="size-2400"
      >
        {(item) => <Item key={item.name}>{item.name}</Item>}
      </ListBox>

      <ListBox
        selectionMode="multiple"
        aria-label="Pick an animal"
        items={options}
        selectedKeys={selectedKeys}
        onSelectionChange={setSelectedKeys}
        width="size-2400"
      >
        {(item) => <Item key={item.name}>{item.name}</Item>}
      </ListBox>
    </Flex>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function Example() {
  let options = [
    { name: 'Koala' },
    { name: 'Kangaroo' },
    { name: 'Platypus' },
    { name: 'Bald Eagle' },
    { name: 'Bison' },
    { name: 'Skunk' }
  ];
  let [selectedKeys, setSelectedKeys] = React.useState<
    Selection
  >(new Set(['Bison']));

  return (
    <Flex direction="row" gap="size-350">
      <ListBox
        selectionMode="multiple"
        aria-label="Pick an animal"
        items={options}
        defaultSelectedKeys={['Bison', 'Koala']}
        width="size-2400"
      >
        {(item) => <Item key={item.name}>{item.name}</Item>}
      </ListBox>

      <ListBox
        selectionMode="multiple"
        aria-label="Pick an animal"
        items={options}
        selectedKeys={selectedKeys}
        onSelectionChange={setSelectedKeys}
        width="size-2400"
      >
        {(item) => <Item key={item.name}>{item.name}</Item>}
      </ListBox>
    </Flex>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function Example() {
  let options = [
    { name: 'Koala' },
    { name: 'Kangaroo' },
    { name: 'Platypus' },
    {
      name: 'Bald Eagle'
    },
    { name: 'Bison' },
    { name: 'Skunk' }
  ];
  let [
    selectedKeys,
    setSelectedKeys
  ] = React.useState<
    Selection
  >(new Set(['Bison']));

  return (
    <Flex
      direction="row"
      gap="size-350"
    >
      <ListBox
        selectionMode="multiple"
        aria-label="Pick an animal"
        items={options}
        defaultSelectedKeys={[
          'Bison',
          'Koala'
        ]}
        width="size-2400"
      >
        {(item) => (
          <Item
            key={item
              .name}
          >
            {item.name}
          </Item>
        )}
      </ListBox>

      <ListBox
        selectionMode="multiple"
        aria-label="Pick an animal"
        items={options}
        selectedKeys={selectedKeys}
        onSelectionChange={setSelectedKeys}
        width="size-2400"
      >
        {(item) => (
          <Item
            key={item
              .name}
          >
            {item.name}
          </Item>
        )}
      </ListBox>
    </Flex>
  );
}
Koala
Kangaroo
Platypus
Bald Eagle
Bison
Skunk
Koala
Kangaroo
Platypus
Bald Eagle
Bison
Skunk

By default, interacting with an item in a ListBox triggers onSelectionChange. Alternatively, items may be links to another page or website. This can be achieved by passing the href prop to the <Item> component. Link items in a ListBox are not selectable.

<ListBox aria-label="Links">
  <Item href="https://adobe.com/" target="_blank">Adobe</Item>
  <Item href="https://apple.com/" target="_blank">Apple</Item>
  <Item href="https://google.com/" target="_blank">Google</Item>
  <Item href="https://microsoft.com/" target="_blank">Microsoft</Item>
</ListBox>
<ListBox aria-label="Links">
  <Item href="https://adobe.com/" target="_blank">
    Adobe
  </Item>
  <Item href="https://apple.com/" target="_blank">
    Apple
  </Item>
  <Item href="https://google.com/" target="_blank">
    Google
  </Item>
  <Item href="https://microsoft.com/" target="_blank">
    Microsoft
  </Item>
</ListBox>
<ListBox aria-label="Links">
  <Item
    href="https://adobe.com/"
    target="_blank"
  >
    Adobe
  </Item>
  <Item
    href="https://apple.com/"
    target="_blank"
  >
    Apple
  </Item>
  <Item
    href="https://google.com/"
    target="_blank"
  >
    Google
  </Item>
  <Item
    href="https://microsoft.com/"
    target="_blank"
  >
    Microsoft
  </Item>
</ListBox>

Client side routing#

The <Item> component works with frameworks and client side routers like Next.js and React Router. As with other React Spectrum components that support links, this works via the Provider component at the root of your app. See the client side routing guide to learn how to set this up.

Sections#


ListBox supports sections in order to group options. Sections can be used by wrapping groups of Items in a Section component. Each Section takes a title and key prop.

Static Items#

<ListBox
  width="size-2400"
  aria-label="Pick your favorite"
  selectionMode="single"
>
  <Section title="Animals">
    <Item key="Aardvark">Aardvark</Item>
    <Item key="Kangaroo">Kangaroo</Item>
    <Item key="Snake">Snake</Item>
  </Section>
  <Section title="People">
    <Item key="Danni">Danni</Item>
    <Item key="Devon">Devon</Item>
    <Item key="Ross">Ross</Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Pick your favorite"
  selectionMode="single"
>
  <Section title="Animals">
    <Item key="Aardvark">Aardvark</Item>
    <Item key="Kangaroo">Kangaroo</Item>
    <Item key="Snake">Snake</Item>
  </Section>
  <Section title="People">
    <Item key="Danni">Danni</Item>
    <Item key="Devon">Devon</Item>
    <Item key="Ross">Ross</Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Pick your favorite"
  selectionMode="single"
>
  <Section title="Animals">
    <Item key="Aardvark">
      Aardvark
    </Item>
    <Item key="Kangaroo">
      Kangaroo
    </Item>
    <Item key="Snake">
      Snake
    </Item>
  </Section>
  <Section title="People">
    <Item key="Danni">
      Danni
    </Item>
    <Item key="Devon">
      Devon
    </Item>
    <Item key="Ross">
      Ross
    </Item>
  </Section>
</ListBox>
Aardvark
Kangaroo
Snake
Danni
Devon
Ross

Dynamic Items#

Sections used with dynamic items are populated from a hierarchical data structure. Similarly to the props on ListBox, Section takes an array of data using the items prop.

import type {Selection} from '@adobe/react-spectrum';

function Example() {
  let options = [
    {name: 'Australian', children: [
      {id: 2, name: 'Koala'},
      {id: 3, name: 'Kangaroo'},
      {id: 4, name: 'Platypus'}
    ]},
    {name: 'American', children: [
      {id: 6, name: 'Bald Eagle'},
      {id: 7, name: 'Bison'},
      {id: 8, name: 'Skunk'}
    ]}
  ];
  let [selected, setSelected] = React.useState<Selection>(new Set());

  return (
    <ListBox
      aria-label="Pick an animal"
      items={options}
      selectedKeys={selected}
      selectionMode="single"
      onSelectionChange={setSelected}
      width="size-2400">
      {item => (
        <Section key={item.name} items={item.children} title={item.name}>
          {item => <Item>{item.name}</Item>}
        </Section>
      )}
    </ListBox>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function Example() {
  let options = [
    {
      name: 'Australian',
      children: [
        { id: 2, name: 'Koala' },
        { id: 3, name: 'Kangaroo' },
        { id: 4, name: 'Platypus' }
      ]
    },
    {
      name: 'American',
      children: [
        { id: 6, name: 'Bald Eagle' },
        { id: 7, name: 'Bison' },
        { id: 8, name: 'Skunk' }
      ]
    }
  ];
  let [selected, setSelected] = React.useState<Selection>(
    new Set()
  );

  return (
    <ListBox
      aria-label="Pick an animal"
      items={options}
      selectedKeys={selected}
      selectionMode="single"
      onSelectionChange={setSelected}
      width="size-2400"
    >
      {(item) => (
        <Section
          key={item.name}
          items={item.children}
          title={item.name}
        >
          {(item) => <Item>{item.name}</Item>}
        </Section>
      )}
    </ListBox>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function Example() {
  let options = [
    {
      name: 'Australian',
      children: [
        {
          id: 2,
          name: 'Koala'
        },
        {
          id: 3,
          name:
            'Kangaroo'
        },
        {
          id: 4,
          name:
            'Platypus'
        }
      ]
    },
    {
      name: 'American',
      children: [
        {
          id: 6,
          name:
            'Bald Eagle'
        },
        {
          id: 7,
          name: 'Bison'
        },
        {
          id: 8,
          name: 'Skunk'
        }
      ]
    }
  ];
  let [
    selected,
    setSelected
  ] = React.useState<
    Selection
  >(new Set());

  return (
    <ListBox
      aria-label="Pick an animal"
      items={options}
      selectedKeys={selected}
      selectionMode="single"
      onSelectionChange={setSelected}
      width="size-2400"
    >
      {(item) => (
        <Section
          key={item.name}
          items={item
            .children}
          title={item
            .name}
        >
          {(item) => (
            <Item>
              {item.name}
            </Item>
          )}
        </Section>
      )}
    </ListBox>
  );
}
Koala
Kangaroo
Platypus
Bald Eagle
Bison
Skunk

Events#


ListBox supports selection via mouse, keyboard, and touch. You can handle all of these via the onSelectionChange prop. ListBox will pass the selected key to the onSelectionChange handler.

The following example uses an onSelectionChange handler to update the selection stored in React state.

import type {Selection} from '@adobe/react-spectrum';

function StaticExample() {
  let [frequency, setFrequency] = React.useState<Selection>(new Set());

  return (
    <>
      <ListBox
        aria-label="Choose frequency"
        selectionMode="single"
        onSelectionChange={selected => setFrequency(selected)}
        width="size-2400">
        <Item key="Rarely">Rarely</Item>
        <Item key="Sometimes">Sometimes</Item>
        <Item key="Always">Always</Item>
      </ListBox>
      <p>You selected: {[...frequency][0]}</p>
    </>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function StaticExample() {
  let [frequency, setFrequency] = React.useState<Selection>(
    new Set()
  );

  return (
    <>
      <ListBox
        aria-label="Choose frequency"
        selectionMode="single"
        onSelectionChange={(selected) =>
          setFrequency(selected)}
        width="size-2400"
      >
        <Item key="Rarely">Rarely</Item>
        <Item key="Sometimes">Sometimes</Item>
        <Item key="Always">Always</Item>
      </ListBox>
      <p>You selected: {[...frequency][0]}</p>
    </>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function StaticExample() {
  let [
    frequency,
    setFrequency
  ] = React.useState<
    Selection
  >(new Set());

  return (
    <>
      <ListBox
        aria-label="Choose frequency"
        selectionMode="single"
        onSelectionChange={(selected) =>
          setFrequency(
            selected
          )}
        width="size-2400"
      >
        <Item key="Rarely">
          Rarely
        </Item>
        <Item key="Sometimes">
          Sometimes
        </Item>
        <Item key="Always">
          Always
        </Item>
      </ListBox>
      <p>
        You selected:
        {' '}
        {[...frequency][
          0
        ]}
      </p>
    </>
  );
}
Rarely
Sometimes
Always

You selected:

When using ListBox with dynamic items, selection works much the same way using key. However, if your data already has an id property (as is common with many data sets), ListBox can use that id without needing to specify a key prop. The below example shows ListBox using the id of each item from the items array as the selected value without the need for key. Note that key will always take precedence if set.

import type {Selection} from '@adobe/react-spectrum';

function DynamicExample() {
  let [animalId, setAnimalId] = React.useState<Selection>(new Set());
  let options = [
    {id: 1, name: 'Aardvark'},
    {id: 2, name: 'Cat'},
    {id: 3, name: 'Dog'},
    {id: 4, name: 'Kangaroo'},
    {id: 5, name: 'Koala'},
    {id: 6, name: 'Penguin'},
    {id: 7, name: 'Snake'},
    {id: 8, name: 'Turtle'},
    {id: 9, name: 'Wombat'}
  ];

  return (
    <>
      <ListBox
        selectionMode="single"
        aria-label="Pick an animal"
        items={options}
        onSelectionChange={selected => setAnimalId(selected)}
        width="size-2400">
        {item => <Item>{item.name}</Item>}
      </ListBox>
      <p>Your favorite animal has id: {[...animalId][0]}</p>
    </>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function DynamicExample() {
  let [animalId, setAnimalId] = React.useState<Selection>(
    new Set()
  );
  let options = [
    { id: 1, name: 'Aardvark' },
    { id: 2, name: 'Cat' },
    { id: 3, name: 'Dog' },
    { id: 4, name: 'Kangaroo' },
    { id: 5, name: 'Koala' },
    { id: 6, name: 'Penguin' },
    { id: 7, name: 'Snake' },
    { id: 8, name: 'Turtle' },
    { id: 9, name: 'Wombat' }
  ];

  return (
    <>
      <ListBox
        selectionMode="single"
        aria-label="Pick an animal"
        items={options}
        onSelectionChange={(selected) =>
          setAnimalId(selected)}
        width="size-2400"
      >
        {(item) => <Item>{item.name}</Item>}
      </ListBox>
      <p>Your favorite animal has id: {[...animalId][0]}</p>
    </>
  );
}
import type {Selection} from '@adobe/react-spectrum';

function DynamicExample() {
  let [
    animalId,
    setAnimalId
  ] = React.useState<
    Selection
  >(new Set());
  let options = [
    {
      id: 1,
      name: 'Aardvark'
    },
    {
      id: 2,
      name: 'Cat'
    },
    {
      id: 3,
      name: 'Dog'
    },
    {
      id: 4,
      name: 'Kangaroo'
    },
    {
      id: 5,
      name: 'Koala'
    },
    {
      id: 6,
      name: 'Penguin'
    },
    {
      id: 7,
      name: 'Snake'
    },
    {
      id: 8,
      name: 'Turtle'
    },
    {
      id: 9,
      name: 'Wombat'
    }
  ];

  return (
    <>
      <ListBox
        selectionMode="single"
        aria-label="Pick an animal"
        items={options}
        onSelectionChange={(selected) =>
          setAnimalId(
            selected
          )}
        width="size-2400"
      >
        {(item) => (
          <Item>
            {item.name}
          </Item>
        )}
      </ListBox>
      <p>
        Your favorite
        animal has id:
        {' '}
        {[...animalId][
          0
        ]}
      </p>
    </>
  );
}
Aardvark
Cat
Dog
Kangaroo
Koala
Penguin
Snake
Turtle
Wombat

Your favorite animal has id:

Complex Items#


Items within ListBox also allow for additional content used to better communicate options. Icons, avatars, and descriptions can be added to the children of Item as shown in the example below. If a description is added, the prop slot="description" must be used to distinguish the different <Text> elements. See Icon's labeling section and Avatar's accessibility section for more information on how to label these elements.

<ListBox width="size-2400" aria-label="Options" selectionMode="single">
  <Section title="Permission">
    <Item textValue="Read">
      <Book size="S" />
      <Text>Read</Text>
      <Text slot="description">Read Only</Text>
    </Item>
    <Item textValue="Write">
      <Draw size="S" />
      <Text>Write</Text>
      <Text slot="description">Read and Write Only</Text>
    </Item>
    <Item textValue="Admin">
      <BulkEditUsers size="S" />
      <Text>Admin</Text>
      <Text slot="description">Full access</Text>
    </Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Options"
  selectionMode="single"
>
  <Section title="Permission">
    <Item textValue="Read">
      <Book size="S" />
      <Text>Read</Text>
      <Text slot="description">Read Only</Text>
    </Item>
    <Item textValue="Write">
      <Draw size="S" />
      <Text>Write</Text>
      <Text slot="description">Read and Write Only</Text>
    </Item>
    <Item textValue="Admin">
      <BulkEditUsers size="S" />
      <Text>Admin</Text>
      <Text slot="description">Full access</Text>
    </Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Options"
  selectionMode="single"
>
  <Section title="Permission">
    <Item textValue="Read">
      <Book size="S" />
      <Text>Read</Text>
      <Text slot="description">
        Read Only
      </Text>
    </Item>
    <Item textValue="Write">
      <Draw size="S" />
      <Text>
        Write
      </Text>
      <Text slot="description">
        Read and Write
        Only
      </Text>
    </Item>
    <Item textValue="Admin">
      <BulkEditUsers size="S" />
      <Text>
        Admin
      </Text>
      <Text slot="description">
        Full access
      </Text>
    </Item>
  </Section>
</ListBox>
ReadRead Only
WriteRead and Write Only
AdminFull access

With avatars#

<ListBox width="size-2400" aria-label="Options" selectionMode="single">
  <Section title="Users">
    <Item textValue="User 1">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 1</Text>
    </Item>
    <Item textValue="User 2">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 2</Text>
    </Item>
    <Item textValue="User 3">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 3</Text>
    </Item>
    <Item textValue="User 4">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 4</Text>
    </Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Options"
  selectionMode="single"
>
  <Section title="Users">
    <Item textValue="User 1">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 1</Text>
    </Item>
    <Item textValue="User 2">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 2</Text>
    </Item>
    <Item textValue="User 3">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 3</Text>
    </Item>
    <Item textValue="User 4">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>User 4</Text>
    </Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Options"
  selectionMode="single"
>
  <Section title="Users">
    <Item textValue="User 1">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>
        User 1
      </Text>
    </Item>
    <Item textValue="User 2">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>
        User 2
      </Text>
    </Item>
    <Item textValue="User 3">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>
        User 3
      </Text>
    </Item>
    <Item textValue="User 4">
      <Avatar src="https://i.imgur.com/kJOwAdv.png" />
      <Text>
        User 4
      </Text>
    </Item>
  </Section>
</ListBox>
User 1
User 2
User 3
User 4

Asynchronous loading#


ListBox supports loading data asynchronously, and will display a progress circle when the isLoading prop is set. It also supports infinite scrolling to load more data on demand as the user scrolls, via the onLoadMore prop.

This example uses the useAsyncList hook to handle loading the data. See the docs for more information.

import {useAsyncList} from 'react-stately';

interface Pokemon {
  name: string;
}

function AsyncLoadingExample() {
  let list = useAsyncList<Pokemon>({
    async load({ signal, cursor }) {
      // If no cursor is available, then we're loading the first page.
      // Otherwise, the cursor is the next URL to load, as returned from the previous page.
      let res = await fetch(cursor || 'https://pokeapi.co/api/v2/pokemon', {
        signal
      });
      let json = await res.json();
      return {
        items: json.results,
        cursor: json.next
      };
    }
  });

  return (
    <Flex maxHeight="size-2400">
      <ListBox
        aria-label="Pick a Pokemon"
        items={list.items}
        isLoading={list.isLoading}
        onLoadMore={list.loadMore}
        width="size-2400"
      >
        {(item) => <Item key={item.name}>{item.name}</Item>}
      </ListBox>
    </Flex>
  );
}
import {useAsyncList} from 'react-stately';

interface Pokemon {
  name: string;
}

function AsyncLoadingExample() {
  let list = useAsyncList<Pokemon>({
    async load({ signal, cursor }) {
      // If no cursor is available, then we're loading the first page.
      // Otherwise, the cursor is the next URL to load, as returned from the previous page.
      let res = await fetch(
        cursor || 'https://pokeapi.co/api/v2/pokemon',
        { signal }
      );
      let json = await res.json();
      return {
        items: json.results,
        cursor: json.next
      };
    }
  });

  return (
    <Flex maxHeight="size-2400">
      <ListBox
        aria-label="Pick a Pokemon"
        items={list.items}
        isLoading={list.isLoading}
        onLoadMore={list.loadMore}
        width="size-2400"
      >
        {(item) => <Item key={item.name}>{item.name}</Item>}
      </ListBox>
    </Flex>
  );
}
import {useAsyncList} from 'react-stately';

interface Pokemon {
  name: string;
}

function AsyncLoadingExample() {
  let list =
    useAsyncList<
      Pokemon
    >({
      async load(
        {
          signal,
          cursor
        }
      ) {
        // If no cursor is available, then we're loading the first page.
        // Otherwise, the cursor is the next URL to load, as returned from the previous page.
        let res =
          await fetch(
            cursor ||
              'https://pokeapi.co/api/v2/pokemon',
            { signal }
          );
        let json =
          await res
            .json();
        return {
          items:
            json.results,
          cursor:
            json.next
        };
      }
    });

  return (
    <Flex maxHeight="size-2400">
      <ListBox
        aria-label="Pick a Pokemon"
        items={list
          .items}
        isLoading={list
          .isLoading}
        onLoadMore={list
          .loadMore}
        width="size-2400"
      >
        {(item) => (
          <Item
            key={item
              .name}
          >
            {item.name}
          </Item>
        )}
      </ListBox>
    </Flex>
  );
}
bulbasaur
ivysaur
venusaur
charmander
charmeleon
charizard
squirtle
wartortle
blastoise
caterpie
metapod
butterfree
weedle
kakuna
beedrill
pidgey
pidgeotto
pidgeot
rattata
raticate
spearow
fearow
ekans
arbok
pikachu
raichu
sandshrew
sandslash
nidoran-f
nidorina
nidoqueen
nidoran-m
nidorino
nidoking
clefairy
clefable
vulpix
ninetales
jigglypuff
wigglytuff
zubat
golbat
oddish
gloom
vileplume
paras
parasect
venonat
venomoth
diglett
dugtrio
meowth
persian
psyduck
golduck
mankey
primeape
growlithe
arcanine
poliwag
poliwhirl
poliwrath
abra
kadabra
alakazam
machop
machoke
machamp
bellsprout
weepinbell
victreebel
tentacool
tentacruel
geodude
graveler
golem
ponyta
rapidash
slowpoke
slowbro
magnemite
magneton
farfetchd
doduo
dodrio
seel
dewgong
grimer
muk
shellder
cloyster
gastly
haunter
gengar
onix
drowzee
hypno
krabby
kingler
voltorb
electrode
exeggcute
exeggutor
cubone
marowak
hitmonlee
hitmonchan
lickitung
koffing
weezing
rhyhorn
rhydon
chansey
tangela
kangaskhan
horsea
seadra
goldeen
seaking
staryu
starmie
mr-mime
scyther
jynx
electabuzz
magmar
pinsir
tauros
magikarp
gyarados
lapras
ditto
eevee
vaporeon
jolteon
flareon
porygon
omanyte
omastar
kabuto
kabutops
aerodactyl
snorlax
articuno
zapdos
moltres
dratini
dragonair
dragonite
mewtwo
mew
chikorita
bayleef
meganium
cyndaquil
quilava
typhlosion
totodile
croconaw
feraligatr
sentret
furret
hoothoot
noctowl
ledyba
ledian
spinarak
ariados
crobat
chinchou
lanturn
pichu
cleffa
igglybuff
togepi
togetic
natu
xatu
mareep
flaaffy
ampharos
bellossom
marill
azumarill
sudowoodo
politoed
hoppip
skiploom
jumpluff
aipom
sunkern
sunflora
yanma
wooper
quagsire
espeon
umbreon
murkrow
slowking
misdreavus
unown
wobbuffet
girafarig
pineco
forretress
dunsparce
gligar
steelix
snubbull
granbull
qwilfish
scizor
shuckle
heracross
sneasel
teddiursa
ursaring
slugma
magcargo
swinub

Props#


NameTypeDescription
children<object>The contents of the collection.
autoFocusbooleanWhether to auto focus the listbox or an option.
shouldFocusWrapbooleanWhether focus should wrap around when the end/start is reached.
itemsIterable<object>Item objects in the collection.
disabledKeysIterable<Key>The item keys that are disabled. These items cannot be selected, focused, or otherwise interacted with.
selectionModeThe type of selection that is allowed in the collection.
disallowEmptySelectionbooleanWhether the collection allows empty selection.
selectedKeys'all'Iterable<Key>The currently selected keys in the collection (controlled).
defaultSelectedKeys'all'Iterable<Key>The initial selected keys in the collection (uncontrolled).
isLoadingbooleanWhether the items are currently loading.
Events
NameTypeDescription
onSelectionChange( (keys: )) => voidHandler that is called when the selection changes.
onFocus( (e: FocusEvent<Target> )) => voidHandler that is called when the element receives focus.
onBlur( (e: FocusEvent<Target> )) => voidHandler that is called when the element loses focus.
onFocusChange( (isFocused: boolean )) => voidHandler that is called when the element's focus status changes.
onLoadMore() => anyHandler that is called when more items should be loaded, e.g. while scrolling near the bottom.
Layout
NameTypeDescription
flex<stringnumberboolean>When used in a flex layout, specifies how the element will grow or shrink to fit the space available. See MDN.
flexGrow<number>When used in a flex layout, specifies how the element will grow to fit the space available. See MDN.
flexShrink<number>When used in a flex layout, specifies how the element will shrink to fit the space available. See MDN.
flexBasis<numberstring>When used in a flex layout, specifies the initial main size of the element. See MDN.
alignSelf<'auto''normal''start''end''center''flex-start''flex-end''self-start''self-end''stretch'>Overrides the alignItems property of a flex or grid container. See MDN.
justifySelf<'auto''normal''start''end''flex-start''flex-end''self-start''self-end''center''left''right''stretch'>Specifies how the element is justified inside a flex or grid container. See MDN.
order<number>The layout order for the element within a flex or grid container. See MDN.
gridArea<string>When used in a grid layout, specifies the named grid area that the element should be placed in within the grid. See MDN.
gridColumn<string>When used in a grid layout, specifies the column the element should be placed in within the grid. See MDN.
gridRow<string>When used in a grid layout, specifies the row the element should be placed in within the grid. See MDN.
gridColumnStart<string>When used in a grid layout, specifies the starting column to span within the grid. See MDN.
gridColumnEnd<string>When used in a grid layout, specifies the ending column to span within the grid. See MDN.
gridRowStart<string>When used in a grid layout, specifies the starting row to span within the grid. See MDN.
gridRowEnd<string>When used in a grid layout, specifies the ending row to span within the grid. See MDN.
Spacing
NameTypeDescription
margin<>The margin for all four sides of the element. See MDN.
marginTop<>The margin for the top side of the element. See MDN.
marginBottom<>The margin for the bottom side of the element. See MDN.
marginStart<>The margin for the logical start side of the element, depending on layout direction. See MDN.
marginEnd<>The margin for the logical end side of an element, depending on layout direction. See MDN.
marginX<>The margin for both the left and right sides of the element. See MDN.
marginY<>The margin for both the top and bottom sides of the element. See MDN.
Sizing
NameTypeDescription
width<>The width of the element. See MDN.
minWidth<>The minimum width of the element. See MDN.
maxWidth<>The maximum width of the element. See MDN.
height<>The height of the element. See MDN.
minHeight<>The minimum height of the element. See MDN.
maxHeight<>The maximum height of the element. See MDN.
Positioning
NameTypeDescription
position<'static''relative''absolute''fixed''sticky'>Specifies how the element is positioned. See MDN.
top<>The top position for the element. See MDN.
bottom<>The bottom position for the element. See MDN.
left<>The left position for the element. See MDN. Consider using start instead for RTL support.
right<>The right position for the element. See MDN. Consider using start instead for RTL support.
start<>The logical start position for the element, depending on layout direction. See MDN.
end<>The logical end position for the element, depending on layout direction. See MDN.
zIndex<number>The stacking order for the element. See MDN.
isHidden<boolean>Hides the element.
Accessibility
NameTypeDescription
idstringThe element's unique identifier. See MDN.
aria-labelstringDefines a string value that labels the current element.
aria-labelledbystringIdentifies the element (or elements) that labels the current element.
aria-describedbystringIdentifies the element (or elements) that describes the object.
aria-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.
Advanced
NameTypeDescription
UNSAFE_classNamestringSets the CSS className for the element. Only use as a last resort. Use style props instead.
UNSAFE_styleCSSPropertiesSets inline style for the element. Only use as a last resort. Use style props instead.

Visual options#


Loading#

<ListBox
  isLoading
  aria-label="Choose frequency"
  selectionMode="single"
  width="size-1200">
  {[]}
</ListBox>
<ListBox
  isLoading
  aria-label="Choose frequency"
  selectionMode="single"
  width="size-1200">
  {[]}
</ListBox>
<ListBox
  isLoading
  aria-label="Choose frequency"
  selectionMode="single"
  width="size-1200"
>
  {[]}
</ListBox>

Disabled#

Use the disabledKeys prop to specify which item keys to disable in the ListBox.

<ListBox
  width="size-2400"
  aria-label="Pick your favorite"
  disabledKeys={['Snake', 'Ross']}
  selectionMode="single"
>
  <Section title="Animals">
    <Item key="Aardvark">Aardvark</Item>
    <Item key="Kangaroo">Kangaroo</Item>
    <Item key="Snake">Snake</Item>
  </Section>
  <Section title="People">
    <Item key="Danni">Danni</Item>
    <Item key="Devon">Devon</Item>
    <Item key="Ross">Ross</Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Pick your favorite"
  disabledKeys={['Snake', 'Ross']}
  selectionMode="single"
>
  <Section title="Animals">
    <Item key="Aardvark">Aardvark</Item>
    <Item key="Kangaroo">Kangaroo</Item>
    <Item key="Snake">Snake</Item>
  </Section>
  <Section title="People">
    <Item key="Danni">Danni</Item>
    <Item key="Devon">Devon</Item>
    <Item key="Ross">Ross</Item>
  </Section>
</ListBox>
<ListBox
  width="size-2400"
  aria-label="Pick your favorite"
  disabledKeys={[
    'Snake',
    'Ross'
  ]}
  selectionMode="single"
>
  <Section title="Animals">
    <Item key="Aardvark">
      Aardvark
    </Item>
    <Item key="Kangaroo">
      Kangaroo
    </Item>
    <Item key="Snake">
      Snake
    </Item>
  </Section>
  <Section title="People">
    <Item key="Danni">
      Danni
    </Item>
    <Item key="Devon">
      Devon
    </Item>
    <Item key="Ross">
      Ross
    </Item>
  </Section>
</ListBox>
Aardvark
Kangaroo
Snake
Danni
Devon
Ross

Testing#


The ListBox features automatic virtualization and may need specific mocks in a test environment to enable said virtualization properly. Please see the following sections in the testing docs for more information on how to handle these behaviors in your test suite.

Timers

Virtualized Components

Please also refer to React Spectrum's test suite if you find that the above isn't sufficient when resolving issues in your own test cases.

Test utils alpha#

@react-spectrum/test-utils offers common listbox interaction utilities which you may find helpful when writing tests. See here for more information on how to setup these utilities in your tests. Below is the full definition of the listbox tester and a sample of how you could use it in your test suite.

// ListBox.test.ts
import {render} from '@testing-library/react';
import {theme} from '@react-spectrum/theme-default';
import {User} from '@react-spectrum/test-utils';

let testUtilUser = new User({ interactionType: 'mouse' });
// ...

it('ListBox can select an option via keyboard', async function () {
  // Render your test component/app and initialize the listbox tester
  let { getByTestId } = render(
    <Provider theme={defaultTheme}>
      <ListBox selectionMode="single" data-testid="test-listbox">
        ...
      </ListBox>
    </Provider>
  );
  let listboxTester = testUtilUser.createTester('ListBox', {
    root: getByTestId('test-listbox'),
    interactionType: 'keyboard'
  });

  await listboxTester.toggleOptionSelection({ option: 4 });
  expect(listboxTester.options()[4]).toHaveAttribute('aria-selected', 'true');
});
// ListBox.test.ts
import {render} from '@testing-library/react';
import {theme} from '@react-spectrum/theme-default';
import {User} from '@react-spectrum/test-utils';

let testUtilUser = new User({ interactionType: 'mouse' });
// ...

it('ListBox can select an option via keyboard', async function () {
  // Render your test component/app and initialize the listbox tester
  let { getByTestId } = render(
    <Provider theme={defaultTheme}>
      <ListBox
        selectionMode="single"
        data-testid="test-listbox"
      >
        ...
      </ListBox>
    </Provider>
  );
  let listboxTester = testUtilUser.createTester('ListBox', {
    root: getByTestId('test-listbox'),
    interactionType: 'keyboard'
  });

  await listboxTester.toggleOptionSelection({ option: 4 });
  expect(listboxTester.options()[4]).toHaveAttribute(
    'aria-selected',
    'true'
  );
});
// ListBox.test.ts
import {render} from '@testing-library/react';
import {theme} from '@react-spectrum/theme-default';
import {User} from '@react-spectrum/test-utils';

let testUtilUser =
  new User({
    interactionType:
      'mouse'
  });
// ...

it('ListBox can select an option via keyboard', async function () {
  // Render your test component/app and initialize the listbox tester
  let { getByTestId } =
    render(
      <Provider
        theme={defaultTheme}
      >
        <ListBox
          selectionMode="single"
          data-testid="test-listbox"
        >
          ...
        </ListBox>
      </Provider>
    );
  let listboxTester =
    testUtilUser
      .createTester(
        'ListBox',
        {
          root:
            getByTestId(
              'test-listbox'
            ),
          interactionType:
            'keyboard'
        }
      );

  await listboxTester
    .toggleOptionSelection(
      { option: 4 }
    );
  expect(
    listboxTester
      .options()[4]
  ).toHaveAttribute(
    'aria-selected',
    'true'
  );
});

Properties

NameTypeDescription
listboxHTMLElementReturns the listbox.
selectedOptionsHTMLElement[]Returns the listbox's selected options if any.
sectionsHTMLElement[]Returns the listbox's sections if any.

Methods

MethodDescription
constructor( (opts: )): void
setInteractionType( (type: ['interactionType'] )): voidSet the interaction type used by the listbox tester.
findOption( (opts: {
optionIndexOrText: numberstring
} )): HTMLElement
Returns a option matching the specified index or text content.
toggleOptionSelection( (opts: )): voidToggles the selection for the specified listbox option. Defaults to using the interaction type set on the listbox tester.
triggerOptionAction( (opts: )): voidTriggers the action for the specified listbox option. Defaults to using the interaction type set on the listbox tester.
options( (opts: {
element?: HTMLElement
} )): HTMLElement[]
Returns the listbox options. Can be filtered to a subsection of the listbox if provided via element.