Skip to content

Commit 87f3f8a

Browse files
Select: scroll selected option into view on open (center); align activeIndex to selected to prevent override
1 parent ee9891f commit 87f3f8a

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

packages/components/src/ui/select.tsx

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export function Select({
6363
if (popoverState.isOpen && selectedItemRef.current) {
6464
// Use setTimeout to ensure the DOM is fully rendered
6565
setTimeout(() => {
66-
selectedItemRef.current?.scrollIntoView({ block: 'nearest' });
66+
selectedItemRef.current?.scrollIntoView({ block: 'center' });
6767
}, 0);
6868
}
6969
}, [popoverState.isOpen]);
@@ -78,7 +78,8 @@ export function Select({
7878
// Reset activeIndex when filtered items change or dropdown opens
7979
React.useEffect(() => {
8080
if (popoverState.isOpen) {
81-
setActiveIndex(0);
81+
const selectedIndex = filtered.findIndex((o) => o.value === value);
82+
setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0);
8283
// Add a small delay to ensure the component is fully initialized
8384
const timer = setTimeout(() => {
8485
setIsInitialized(true);
@@ -87,14 +88,14 @@ export function Select({
8788
} else {
8889
setIsInitialized(false);
8990
}
90-
}, [filtered, popoverState.isOpen]);
91+
}, [filtered, popoverState.isOpen, value]);
9192

9293
// Scroll active item into view when activeIndex changes
9394
React.useEffect(() => {
9495
if (popoverState.isOpen && listContainerRef.current && filtered.length > 0) {
9596
const activeElement = listContainerRef.current.querySelector(`[data-index="${activeIndex}"]`) as HTMLElement;
9697
if (activeElement) {
97-
activeElement.scrollIntoView({ block: 'nearest' });
98+
activeElement.scrollIntoView({ block: 'center' });
9899
}
99100
}
100101
}, [activeIndex, popoverState.isOpen, filtered.length]);

0 commit comments

Comments
 (0)