Skip to content

Fixing fully controlled combobox aria example #1576

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 16, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions packages/@react-aria/combobox/docs/useComboBox.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -477,19 +477,20 @@ function ControlledComboBox() {

// Implement custom filtering logic and control what items are
// available to the ComboBox.
// Memoize filteredItems so it updates when the inputValue updates.
let {startsWith} = useFilter({sensitivity: 'base'});
let filteredItems = React.useMemo(() => optionList.filter(item => startsWith(item.name, fieldState.inputValue)), [optionList, fieldState.inputValue]);

// Specify how each of the ComboBox values should change when an
// option is selected from the list box
let onSelectionChange = (key) => {
setFieldState(prevState => ({
isOpen: false,
inputValue: prevState.items.find(option => option.id === key)?.name ?? '',
selectedKey: key,
items: prevState.items
}));
setFieldState(prevState => {
let selectedItem = prevState.items.find(option => option.id === key);
return ({
isOpen: false,
inputValue: selectedItem?.name ?? '',
selectedKey: key,
items: optionList.filter(item => startsWith(item.name, selectedItem?.name ?? ''))
})
});
};

// Specify how each of the ComboBox values should change when the input
Expand All @@ -499,7 +500,7 @@ function ControlledComboBox() {
isOpen: true,
inputValue: value,
selectedKey: value === '' ? null : prevState.selectedKey,
items: filteredItems
items: optionList.filter(item => startsWith(item.name, value))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was broken because the memoized filteredItems is one step behind the user input (aka the latest input value is set after this setState but the items set here were based on the previous input value). This should fix

}));
};

Expand All @@ -519,10 +520,10 @@ function ControlledComboBox() {
return (
<ComboBox
label="Favorite Animal"
items={filteredItems}
items={fieldState.items}
selectedKey={fieldState.selectedKey}
inputValue={fieldState.inputValue}
isOpen={fieldState.isOpen && filteredItems.length > 0}
isOpen={fieldState.isOpen && fieldState.items.length > 0}
onOpenChange={onOpenChange}
onSelectionChange={onSelectionChange}
onInputChange={onInputChange}>
Expand Down