diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 3ac34c758c98..e81bbb27d20e 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -1,8 +1,8 @@ import {useFocusEffect, useIsFocused} from '@react-navigation/native'; -import React, {forwardRef, useCallback, useEffect, useMemo, useRef, useState} from 'react'; import type {ForwardedRef} from 'react'; -import {View} from 'react-native'; +import React, {forwardRef, useCallback, useEffect, useMemo, useRef, useState} from 'react'; import type {LayoutChangeEvent, SectionList as RNSectionList, TextInput as RNTextInput, SectionListRenderItemInfo} from 'react-native'; +import {View} from 'react-native'; import ArrowKeyFocusManager from '@components/ArrowKeyFocusManager'; import Button from '@components/Button'; import Checkbox from '@components/Checkbox'; @@ -16,6 +16,7 @@ import TextInput from '@components/TextInput'; import useActiveElementRole from '@hooks/useActiveElementRole'; import useKeyboardShortcut from '@hooks/useKeyboardShortcut'; import useLocalize from '@hooks/useLocalize'; +import usePrevious from '@hooks/usePrevious'; import useThemeStyles from '@hooks/useThemeStyles'; import Log from '@libs/Log'; import variables from '@styles/variables'; @@ -347,18 +348,17 @@ function BaseSelectionList( }, [shouldShowTextInput]), ); + const prevTextInputValue = usePrevious(textInputValue); useEffect(() => { - // do not change focus on the first render, as it should focus on the selected item - if (isInitialSectionListRender) { + // Avoid changing focus if the textInputValue remains unchanged. + if (prevTextInputValue === textInputValue || 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; - // set the focus on the first item when the sections list is changed - if (sections.length > 0) { - updateAndScrollToFocusedIndex(0); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [sections]); + updateAndScrollToFocusedIndex(newSelectedIndex); + }, [canSelectMultiple, flattenedSections.allOptions.length, prevTextInputValue, textInputValue, updateAndScrollToFocusedIndex]); /** Selects row when pressing Enter */ useKeyboardShortcut(CONST.KEYBOARD_SHORTCUTS.ENTER, selectFocusedOption, {