From 5d4e0d513a2cb046bdd22fc9d42c0b7c6661aec9 Mon Sep 17 00:00:00 2001 From: Victoria Zhizhonkova Date: Wed, 22 Jan 2025 13:33:28 +0000 Subject: [PATCH] fix(CustomSelect): auto scroll only on open --- .../components/CustomSelect/CustomSelect.tsx | 32 ++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/packages/vkui/src/components/CustomSelect/CustomSelect.tsx b/packages/vkui/src/components/CustomSelect/CustomSelect.tsx index a0cefb3333..fe731b9cf1 100644 --- a/packages/vkui/src/components/CustomSelect/CustomSelect.tsx +++ b/packages/vkui/src/components/CustomSelect/CustomSelect.tsx @@ -309,6 +309,7 @@ export function CustomSelect(null); const selectElRef = useExternRef(getRef); const optionsWrapperRef = React.useRef(null); + const scrollPerformedRef = React.useRef(false); const [focusedOptionIndex, setFocusedOptionIndex] = React.useState(-1); const [isControlledOutside, setIsControlledOutside] = React.useState(props.value !== undefined); @@ -426,18 +427,27 @@ export function CustomSelect { - scrollBoxRef.current = ref; + const setScrollBoxRef = React.useCallback((ref: HTMLDivElement | null) => { + scrollBoxRef.current = ref; + }, []); - if (ref && selectedOptionIndex !== undefined && isValidIndex(selectedOptionIndex)) { - { - scrollToElement(selectedOptionIndex, true); - } - } - }, - [isValidIndex, scrollToElement, selectedOptionIndex], - ); + useIsomorphicLayoutEffect(() => { + if (!opened) { + scrollPerformedRef.current = false; + return; + } + + if (scrollPerformedRef.current) { + return; + } + + const isIndexValid = selectedOptionIndex !== undefined && isValidIndex(selectedOptionIndex); + + if (scrollBoxRef.current && isIndexValid) { + scrollPerformedRef.current = true; + scrollToElement(selectedOptionIndex, true); + } + }, [opened, selectedOptionIndex, scrollToElement, isValidIndex]); const [keyboardInput, setKeyboardInput] = React.useState(''); const resetKeyboardInput = React.useCallback(() => {