diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index b47d920713a..74b338b57e5 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -401,18 +401,29 @@ function BaseSelectionList( ); const prevTextInputValue = usePrevious(textInputValue); + const prevSelectedOptionsLength = usePrevious(flattenedSections.selectedOptions.length); + useEffect(() => { // Avoid changing focus if the textInputValue remains unchanged. - if (prevTextInputValue === textInputValue || flattenedSections.allOptions.length === 0) { + if ((prevTextInputValue === textInputValue && flattenedSections.selectedOptions.length === prevSelectedOptionsLength) || flattenedSections.allOptions.length === 0) { return; } - // Remove the focus if the search input is empty else focus on the first non disabled item - const newSelectedIndex = textInputValue === '' ? -1 : 0; + // Remove the focus if the search input is empty or selected options length is changed else focus on the first non disabled item + const newSelectedIndex = textInputValue === '' || flattenedSections.selectedOptions.length !== prevSelectedOptionsLength ? -1 : 0; + // reseting the currrent page to 1 when the user types something setCurrentPage(1); updateAndScrollToFocusedIndex(newSelectedIndex); - }, [canSelectMultiple, flattenedSections.allOptions.length, prevTextInputValue, textInputValue, updateAndScrollToFocusedIndex]); + }, [ + canSelectMultiple, + flattenedSections.allOptions.length, + flattenedSections.selectedOptions.length, + prevTextInputValue, + textInputValue, + updateAndScrollToFocusedIndex, + prevSelectedOptionsLength, + ]); useEffect( () => () => {