useSelect
useSelect turns a button and a list of options into a
select-only combobox with keyboard navigation and typeahead.
Quickstart
import React from 'react'
import {useSelect} from 'downshift'
const items = ['Apple', 'Apricot', 'Banana']
export default function FruitSelect() {
const select = useSelect({items})
return (
<div>
<label {...select.getLabelProps()}>Choose a fruit</label>
<button type="button" {...select.getToggleButtonProps()}>
{select.selectedItem || 'Select a fruit'}
</button>
<ul {...select.getMenuProps()} hidden={!select.isOpen}>
{items.map((item, index) => (
<li
key={item}
{...select.getItemProps({item, index})}
style={{fontWeight: select.highlightedIndex === index ? 'bold' : 'normal'}}
>
{item}
</li>
))}
</ul>
</div>
)
}
Focus the button, press Arrow Down to highlight a fruit, then press Enter to
select it.
Using object items
When each item is a book, pass itemToString so typing a title moves the
highlight to that book. The button displays the selected book's title.
Open the book example in CodeSandbox.
function SelectExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function Select() {
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: books,
itemToString,
})
return (
<div>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between cursor-pointer"
{...getToggleButtonProps()}
>
<span>{selectedItem ? selectedItem.title : 'Best book ever'}</span>
<span className="px-2">{isOpen ? <>↑</> : <>↓</>}</span>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps()}
>
{isOpen &&
books.map((item, index) => (
<li
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === item &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex flex-col text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({item, index})}
>
<span>{item.title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{item.author}
</span>
</li>
))}
</ul>
</div>
)
}
return <Select />
}
Props used in examples
| Returned prop | Element | Purpose |
|---|
getLabelProps | <label> | Labels the toggle. |
getToggleButtonProps | <button> | Opens the list and handles keyboard navigation. The book example uses a <div> for the toggle. |
getMenuProps | <ul> | Identifies the listbox. |
getItemProps | <li> | Wires each option to its item and index. |
isOpen | | Whether the list is open. |
highlightedIndex | | Index of the highlighted option, or -1 when none is highlighted. |
selectedItem | | The item to display on the toggle. |
See the useSelect API reference for all props and return values.
Disabled options
Open the list and use the arrow keys to move from Piranesi to Middlemarch.
War and Peace is on loan, so the highlight skips it and clicking it leaves
the selection unchanged. Pass isItemDisabled to useSelect.
getItemProps then sets aria-disabled on the option and handles the
interaction. The visible “on loan” text explains why the book is unavailable.
const books = [
{title: 'Piranesi', onLoan: false},
{title: 'War and Peace', onLoan: true},
{title: 'Middlemarch', onLoan: false},
]
function AvailableBookSelect() {
const {
isOpen,
selectedItem,
highlightedIndex,
getLabelProps,
getToggleButtonProps,
getMenuProps,
getItemProps,
} = useSelect({
items: books,
itemToString: book => (book ? book.title : ''),
isItemDisabled: book => book.onLoan,
})
return (
<div>
<label {...getLabelProps()}>Choose a book to borrow</label>
<button
type="button"
className="block border rounded px-2"
{...getToggleButtonProps()}
>
{selectedItem ? selectedItem.title : 'Select a book'}
</button>
<ul {...getMenuProps()} hidden={!isOpen}>
{isOpen &&
books.map((book, index) => (
<li
key={book.title}
className={cx(
highlightedIndex === index && 'underline',
book.onLoan && 'italic cursor-not-allowed',
)}
{...getItemProps({item: book, index})}
>
{book.title}
{book.onLoan && ' (on loan)'}
</li>
))}
</ul>
</div>
)
}
render(<AvailableBookSelect />)
React Native
The hook can be used with React Native as well. The HTML elements and styles
are replaced with React Native equivalents, but the useSelect usage is exactly
the same as on React web.
MaterialUI
A custom select element can be created using UI Library components as well.
Many libraries provide basic elements such as buttons, texts/labels, and lists,
which can be styled according to each library guidelines. useSelect provides
the additional stateful logic to transform this selection of basic components
into a fully working dropdown element.
As useSelect needs to perform some focus() and scroll() logic on the
DOM elements, it requires refs to the React components used. This example
illustrates how to use useSelect with MaterialUI, and shows how to correctly
pass refs to the hook.
Since MaterialUI components already accept a ref prop that will be filled
with the resulting DOM element, we don't need to do anything specific other than
just spreading the getter props.
itemToString returns a book's title so users can type the first letters of a
title to find it. The button also uses that function to display the selected
book. In v9, custom live region messages are opt-in. To announce a custom
selection message, pass getA11yStatusMessage to useSelect.
CodeSandbox for MaterialUI usage example.
function SelectExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function Select() {
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: books,
itemToString,
})
return (
<Box>
<Box className="w-72 flex flex-col gap-1">
<FormLabel className="w-fit" {...getLabelProps()}>
Choose your favorite book:
</FormLabel>
<Button
component="div"
variant="contained"
color="secondary"
className="flex !justify-between"
{...getToggleButtonProps()}
>
{selectedItem ? itemToString(selectedItem) : 'Best book ever'}
{isOpen ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</Button>
</Box>
<List
className={cx(
!isOpen && 'hidden',
'!absolute bg-white dark:bg-zinc-900 w-72 shadow-md max-h-80 overflow-scroll',
)}
{...getMenuProps()}
>
{isOpen &&
books.map((item, index) => {
return (
<ListItem
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === item &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({
item,
index,
})}
>
<ListItemText
primary={item.title}
secondary={item.author}
primaryTypographyProps={{
className: 'text-zinc-900 dark:text-zinc-100',
}}
secondaryTypographyProps={{
className: 'text-zinc-600 dark:text-zinc-300',
}}
/>
</ListItem>
)
})}
</List>
</Box>
)
}
return <Select />
}
Controlling state
Controlling state is possible by receiving the state changes handled by
Downshift via onChange props (onHighlightedIndexChange, onSelectedItemChange
etc.), changing data based on your requirements, and passing the data back to
Downshift via props, for instance highlightedIndex or selectedItem.
The example below shows how to control selectedItem. Both select elements
share the same selectedItem reference, and changing it in one of the dropdowns
will update the value in the other one as well.
CodeSandbox for controlling state example.
function SelectExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function Select() {
const [selectedItem, setSelectedItem] = React.useState(null)
const {
isOpen,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: books,
itemToString,
selectedItem,
onSelectedItemChange: ({selectedItem: newSelectedItem}) =>
setSelectedItem(newSelectedItem),
})
return (
<div>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between cursor-pointer"
{...getToggleButtonProps()}
>
<span>{selectedItem ? selectedItem.title : 'Best book ever'}</span>
<span className="px-2">{isOpen ? <>↑</> : <>↓</>}</span>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps()}
>
{isOpen &&
books.map((item, index) => (
<li
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === item &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex flex-col text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({item, index})}
>
<span>{item.title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{item.author}
</span>
</li>
))}
</ul>
<p className="font-semibold">
{selectedItem
? `You have selected ${selectedItem.title} by ${selectedItem.author}.`
: 'Select a book!'}
</p>
</div>
)
}
return <Select />
}
State Reducer
For even more granular state change control, you can add your own reducer on top
of the default one. When the stateReducer is called, it will receive the
previous state and the actionAndChanges object as parameters.
actionAndChanges contains the change type, which explains why the state is
being changed. It also contains the changes proposed by useSelect that
should occur as a consequence of that change type. You are supposed to return
the new state according to your needs.
In the example below, we are implementing a Windows-specific behavior for the
select. While menu is closed, using ArrowUp and ArrowDown should keep the
menu closed and change selectedItem incrementally or decrementally. In the
stateReducer we capture the ToggleButtonKeyDownArrowDown and
ToggleButtonKeyDownArrowUp events, compute the next selectedItem based on
index, and return it without any other changes.
In all other state change types, we return useSelect default changes.
CodeSandbox for state reducer example.
function SelectExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function stateReducer(state, actionAndChanges) {
const {type, changes} = actionAndChanges
if (state.isOpen) {
return changes
}
switch (type) {
case useSelect.stateChangeTypes.ToggleButtonKeyDownArrowDown:
const nextItemIndex = books.indexOf(state.selectedItem)
if (nextItemIndex === books.length - 1) {
return {selectedItem: books[0]}
}
return {selectedItem: books[nextItemIndex + 1]}
case useSelect.stateChangeTypes.ToggleButtonKeyDownArrowUp:
const previousItemIndex = books.indexOf(state.selectedItem)
if (previousItemIndex === 0) {
return {selectedItem: books[books.length - 1]}
}
return {selectedItem: books[previousItemIndex - 1]}
default:
return changes
}
}
function Select() {
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: books,
itemToString,
stateReducer,
})
return (
<div>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between cursor-pointer"
{...getToggleButtonProps()}
>
<span>{selectedItem ? selectedItem.title : 'Best book ever'}</span>
<span className="px-2">{isOpen ? <>↑</> : <>↓</>}</span>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps()}
>
{isOpen &&
books.map((item, index) => (
<li
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === item &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex flex-col text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({item, index})}
>
<span>{item.title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{item.author}
</span>
</li>
))}
</ul>
</div>
)
}
return <Select />
}
Outside dismissal
Open Book filter, focus Choose a book, and press Arrow Down to highlight
a title. Click outside the popover to dismiss it and keep the previous
selection. Repeat with Tab to accept the highlighted book and move to Done.
The native popover handles outside dismissal. Since v9.5, an outside mouse or
touch interaction sets source to 'outside' on Downshift's ToggleButtonBlur
action. The reducer lets the list close and preserves the selected book in that
case. A blur from tabbing away uses Downshift's default changes.
function BookFilter() {
const books = ['Piranesi', 'Middlemarch', 'Persuasion']
const {
isOpen,
selectedItem,
highlightedIndex,
getLabelProps,
getToggleButtonProps,
getMenuProps,
getItemProps,
} = useSelect({
items: books,
stateReducer(state, {type, source, changes}) {
if (
type === useSelect.stateChangeTypes.ToggleButtonBlur &&
source === 'outside'
) {
return {...changes, selectedItem: state.selectedItem}
}
return changes
},
})
return (
<div>
<button
type="button"
popovertarget="book-filter"
className="border rounded px-2"
>
Book filter
</button>
<p>Selected book: {selectedItem || 'None'}</p>
<div
id="book-filter"
popover="auto"
className="m-auto border rounded p-4"
>
<label {...getLabelProps()}>Choose a book</label>
<button
type="button"
className="block border rounded px-2"
{...getToggleButtonProps()}
>
{selectedItem || 'Select a book'}
</button>
<ul {...getMenuProps()} hidden={!isOpen}>
{isOpen &&
books.map((book, index) => (
<li
key={book}
className={highlightedIndex === index ? 'underline' : ''}
{...getItemProps({item: book, index})}
>
{book}
</li>
))}
</ul>
<button
type="button"
popovertarget="book-filter"
popovertargetaction="hide"
>
Done
</button>
</div>
</div>
)
}
Custom window
When using useSelect in an iframe or in any other scenario that uses a
window object different than the default browser window, it is required to
provide that window object to the hook as well. Internally, we rely on the
window for DOM related logic and working with the wrong object will make the
hook behave unexpectedly. For example, when using react-frame-component to
produce an iframe container, we should pass its window object to the hook
like shown below.
CodeSandbox for custom window example.
function SelectExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function Select() {
const {window} = useFrame()
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: books,
itemToString,
environment: window,
})
return (
<div>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between cursor-pointer"
{...getToggleButtonProps()}
>
<span>{selectedItem ? selectedItem.title : 'Best book ever'}</span>
<span className="px-2">{isOpen ? <>↑</> : <>↓</>}</span>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps()}
>
{isOpen &&
books.map((item, index) => (
<li
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === item &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex flex-col text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({item, index})}
>
<span>{item.title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{item.author}
</span>
</li>
))}
</ul>
</div>
)
}
return (
<Frame className="h-60 w-full">
<link href="/styles.css" rel="stylesheet" />
<Select />
</Frame>
)
}
Basic Multiple selection
Select any number of books from the list. To display selected items as removable
tags, see the
useTagGroup example.
In the example below, we control the selectedItem to always be null and keep
our selected items in a state variable, selectedItems. We use
onSelectedItemChange prop to retrieve the selectedItem from useSelect,
which is added to / removed from the selectedItems array. We also use
stateReducer to keep the menu open on selection by Enter key or by click, and
also to keep the highlightedIndex to be the most recent selected item.
The listbox has aria-multiselectable="true", and each option exposes its
selection state through aria-selected. A decorative checkmark shows which
books are selected.
CodeSandbox for basic multiple selection
example.
function SelectExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function stateReducer(state, actionAndChanges) {
const {changes, type} = actionAndChanges
switch (type) {
case useSelect.stateChangeTypes.ToggleButtonKeyDownEnter:
case useSelect.stateChangeTypes.ToggleButtonKeyDownSpaceButton:
case useSelect.stateChangeTypes.ItemClick:
return {
...changes,
isOpen: true,
highlightedIndex: state.highlightedIndex,
}
default:
return changes
}
}
function Select() {
const [selectedItems, setSelectedItems] = useState([])
const {
isOpen,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: books,
itemToString,
stateReducer,
selectedItem: null,
onSelectedItemChange: ({selectedItem}) => {
if (!selectedItem) {
return
}
const index = selectedItems.indexOf(selectedItem)
if (index > 0) {
setSelectedItems([
...selectedItems.slice(0, index),
...selectedItems.slice(index + 1),
])
} else if (index === 0) {
setSelectedItems([...selectedItems.slice(1)])
} else {
setSelectedItems([...selectedItems, selectedItem])
}
},
})
const buttonText = selectedItems.length
? `${selectedItems.length} books selected.`
: 'Best books ever.'
return (
<div>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between cursor-pointer"
{...getToggleButtonProps()}
>
<span>{buttonText}</span>
<span className="px-2">{isOpen ? <>↑</> : <>↓</>}</span>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps({'aria-multiselectable': true})}
>
{isOpen &&
books.map((item, index) => (
<li
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItems.includes(item) &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex gap-3 items-center text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({
item,
index,
'aria-selected': selectedItems.includes(item),
})}
>
<span aria-hidden="true" className="w-5 shrink-0">
{selectedItems.includes(item) ? '✓' : ''}
</span>
<div className="flex flex-col">
<span>{item.title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{item.author}
</span>
</div>
</li>
))}
</ul>
</div>
)
}
return <Select />
}
Multiple selection with Tag Group
If your multiple selection scenario uses a tag group to display selected items,
you can use the hook in combination with useTagGroup.
In the example below, we use:
- null to control selectedItem as the hook should not care about
selection.
- onSelectedItemChange to be able to call addItem from useTagGroup.
- stateReducer to keep the menu open on selection.
CodeSandbox for combobox with tag group
example.
function TagGroupExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function TagGroup() {
const initialItems = books.slice(0, 2)
const [inputValue, setInputValue] = React.useState('')
const {
addItem,
getTagProps,
getTagRemoveProps,
getTagGroupProps,
items,
activeIndex,
} = useTagGroup({
initialItems,
})
const itemsToAdd = books.filter(
book =>
!items.includes(book) &&
(!inputValue ||
book.title.toLowerCase().includes(inputValue.toLowerCase()) ||
book.author.toLowerCase().includes(inputValue.toLowerCase())),
)
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: itemsToAdd,
itemToString,
onSelectedItemChange({selectedItem}) {
if (selectedItem) {
addItem(selectedItem)
}
},
selectedItem: null,
itemToString(item) {
return item ? item.title : ''
},
stateReducer(_state, actionAndChanges) {
const {changes, type} = actionAndChanges
if (
changes.selectedItem &&
type !== useSelect.stateChangeTypes.ToggleButtonBlur
) {
return {...changes, inputValue: '', highlightedIndex: 0, isOpen: true}
}
return changes
},
})
return (
<div>
<div
{...getTagGroupProps({'aria-label': 'books usage example'})}
className="inline-flex gap-2 items-center flex-wrap p-1.5"
>
{items.map((item, index) => (
<span
className={`${
index === activeIndex ? 'italic' : ''
} border border-green-800 bg-green-600 px-1.5 mx-0.5 rounded-[10px] cursor-default hover:opacity-50 focus:bg-red-600 focus:border-red-800`}
key={item.id}
{...getTagProps({index, 'aria-label': item.title})}
>
{item.title}
<span
className="p-1 cursor-pointer border-0 bg-transparent"
{...getTagRemoveProps({index, 'aria-label': 'remove'})}
>
✕
</span>
</span>
))}
</div>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between cursor-pointer"
{...getToggleButtonProps()}
>
<span>{selectedItem ? selectedItem.title : 'Best book ever'}</span>
<span className="px-2">{isOpen ? <>↑</> : <>↓</>}</span>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps()}
>
{isOpen &&
itemsToAdd.map((item, index) => (
<li
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === item &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex flex-col text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({item, index})}
>
<span>{item.title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{item.author}
</span>
</li>
))}
</ul>
</div>
)
}
return <TagGroup />
}
Using action props
Action props are functions returned by useSelect along with the state props
and getter props. They are handy when you need to execute select state changes
from event handlers, state change handlers or any other external location. In
the example below we open the menu when the toggle button is hovered, and clear
the selection by clicking on the custom selection clearing button. We use the
openMenu and selectItem action props in order to achieve these custom
behaviors.
CodeSandbox for action props example.
function SelectExample() {
const books = [
{id: 'book-1', author: 'Harper Lee', title: 'To Kill a Mockingbird'},
{id: 'book-2', author: 'Lev Tolstoy', title: 'War and Peace'},
{id: 'book-3', author: 'Fyodor Dostoevsky', title: 'The Idiot'},
{id: 'book-4', author: 'Oscar Wilde', title: 'A Picture of Dorian Gray'},
{id: 'book-5', author: 'George Orwell', title: '1984'},
{id: 'book-6', author: 'Jane Austen', title: 'Pride and Prejudice'},
{id: 'book-7', author: 'Marcus Aurelius', title: 'Meditations'},
{
id: 'book-8',
author: 'Fyodor Dostoevsky',
title: 'The Brothers Karamazov',
},
{id: 'book-9', author: 'Lev Tolstoy', title: 'Anna Karenina'},
{id: 'book-10', author: 'Fyodor Dostoevsky', title: 'Crime and Punishment'},
]
function itemToString(item) {
return item ? item.title : ''
}
function Select() {
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
openMenu,
closeMenu,
selectItem,
} = useSelect({
items: books,
itemToString,
})
return (
<div onMouseLeave={closeMenu}>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div className="flex justify-between">
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between grow cursor-pointer"
{...getToggleButtonProps({
onMouseEnter() {
openMenu()
},
})}
>
<span>
{selectedItem ? selectedItem.title : 'Best book ever'}
</span>
<span className="px-2">
{isOpen ? <>↑</> : <>↓</>}
</span>
</div>
<button
aria-label="clear selection"
className="p-2 bg-white dark:bg-zinc-900"
type="button"
onClick={() => {
selectItem(null)
}}
>
×
</button>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps()}
>
{isOpen &&
books.map((item, index) => (
<li
className={cx(
highlightedIndex === index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === item &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex flex-col text-zinc-900 dark:text-zinc-100',
)}
key={item.id}
{...getItemProps({item, index})}
>
<span>{item.title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{item.author}
</span>
</li>
))}
</ul>
</div>
)
}
return <Select />
}
Virtualizing items with react-virtual
When the number of items in the dropdown is too big, you may want to consider
using a virtualization technique to avoid loss in performance due to unnecessary
elements rendered in the DOM. react-virtual is a great
library to provide items virtualization and it's the one we will show in the
example below. There are other libraries as well, such as
react-virtualized and
react-virtual.
Since react-virtual has its own scrolling library, we will use it instead of
the default one from Downshift. Apart from this it's business as usual in both
the case of using useSelect and useVirtual, about which you can learn in the
react-virtual github link.
CodeSandbox for virtualized list example.
function SelectExample() {
const books = []
for (let index = 1; index <= 1000; index++) {
books.push({author: `Author ${index}`, title: `Book Number ${index}`})
}
function itemToString(item) {
return item ? item.title : ''
}
function estimateSize() {
return 60
}
function Select() {
const listRef = React.useRef()
const rowVirtualizer = useVirtual({
size: books.length,
parentRef: listRef,
estimateSize,
overscan: 2,
})
const {
isOpen,
selectedItem,
getToggleButtonProps,
getLabelProps,
getMenuProps,
highlightedIndex,
getItemProps,
} = useSelect({
items: books,
itemToString,
scrollIntoView() {},
onHighlightedIndexChange: ({highlightedIndex, type}) => {
if (type !== useSelect.stateChangeTypes.MenuMouseLeave) {
rowVirtualizer.scrollToIndex(highlightedIndex)
}
},
})
return (
<div>
<div className="w-72 flex flex-col gap-1">
<label {...getLabelProps()}>Choose your favorite book:</label>
<div
className="p-2 bg-white dark:bg-zinc-900 flex justify-between cursor-pointer"
{...getToggleButtonProps()}
>
<span>{selectedItem ? selectedItem.title : 'Best book ever'}</span>
<span className="px-2">{isOpen ? <>↑</> : <>↓</>}</span>
</div>
</div>
<ul
className={`absolute w-72 bg-white dark:bg-zinc-900 mt-1 shadow-md max-h-80 overflow-scroll p-0 z-10 ${
!isOpen && 'hidden'
}`}
{...getMenuProps({ref: listRef})}
>
{isOpen && (
<>
<li key="total-size" style={{height: rowVirtualizer.totalSize}} />
{rowVirtualizer.virtualItems.map(virtualRow => (
<li
className={cx(
highlightedIndex === virtualRow.index &&
'bg-blue-300 !text-black dark:bg-sky-700 dark:!text-white',
selectedItem === books[virtualRow.index] &&
'font-bold !text-black dark:!text-white',
'py-2 px-3 shadow-sm flex flex-col text-zinc-900 dark:text-zinc-100',
)}
key={virtualRow.key}
{...getItemProps({
index: virtualRow.index,
item: books[virtualRow.index],
})}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: virtualRow.size,
transform: `translateY(${virtualRow.start}px)`,
}}
>
<span>{books[virtualRow.index].title}</span>
<span className="text-sm text-zinc-600 dark:text-zinc-300">
{books[virtualRow.index].author}
</span>
</li>
))}
</>
)}
</ul>
</div>
)
}
return <Select />
}
Breaking Changes in v8 and v9
useSelect has been affected by breaking changes in v8 and v9, so check out the
migration pages for v8 and v9.
Breaking Changes in v7
Since version 7, useSelect supports the ARIA 1.2 pattern for the combobox,
which contains some changes from the ARIA 1.1 pattern. This brings changes in
the API and the behaviour of useSelect, detailed in the migration
page.
Other usage examples
To see more cool stuff you can build with useSelect, explore the examples
repository.