Skip to content

Commit

Permalink
Improve default selection in the Combobox Component (#33928)
Browse files Browse the repository at this point in the history
* Set default selection to the current option value

* If suggestions change, update current selection

* Update packages/components/src/combobox-control/index.js

Co-authored-by: sarayourfriend <[email protected]>

* clean up source and typo

* Improve variable naming for clarity

Co-authored-by: sarayourfriend <[email protected]>
  • Loading branch information
mikejolley and sarayourfriend authored Aug 13, 2021
1 parent b77066b commit 462ba4f
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions packages/components/src/combobox-control/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,15 @@ function ComboboxControl( {
selected: __( 'Item selected.' ),
},
} ) {
const currentOption = options.find( ( option ) => option.value === value );
const currentLabel = currentOption?.label ?? '';
const instanceId = useInstanceId( ComboboxControl );
const [ selectedSuggestion, setSelectedSuggestion ] = useState( null );
const [ selectedSuggestion, setSelectedSuggestion ] = useState(
currentOption || null
);
const [ isExpanded, setIsExpanded ] = useState( false );
const [ inputValue, setInputValue ] = useState( '' );
const inputContainer = useRef();
const currentOption = options.find( ( option ) => option.value === value );
const currentLabel = currentOption?.label ?? '';

const matchingSuggestions = useMemo( () => {
const startsWithMatch = [];
Expand Down Expand Up @@ -159,6 +161,18 @@ function ComboboxControl( {
inputContainer.current.input.focus();
};

// Update current selections when the filter input changes.
useEffect( () => {
const hasMatchingSuggestions = matchingSuggestions.length > 0;
const hasSelectedMatchingSuggestions =
matchingSuggestions.indexOf( selectedSuggestion ) > 0;

if ( hasMatchingSuggestions && ! hasSelectedMatchingSuggestions ) {
// If the current selection isn't present in the list of suggestions, then automatically select the first item from the list of suggestions.
setSelectedSuggestion( matchingSuggestions[ 0 ] );
}
}, [ matchingSuggestions, selectedSuggestion ] );

// Announcements
useEffect( () => {
const hasMatchingSuggestions = matchingSuggestions.length > 0;
Expand Down

0 comments on commit 462ba4f

Please sign in to comment.