Skip to content

Commit

Permalink
Fix Dropown autoscroll (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
AyIong authored Jan 3, 2025
1 parent 00c71ef commit 0957e74
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/components/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export function Dropdown(props: Props) {
const selectedIndex =
options.findIndex((option) => getOptionValue(option) === selected) || 0;

function scrollTo(position: number) {
function scrollToElement(position: number) {
let scrollPos = position;
if (position < selectedIndex) {
scrollPos = position < 2 ? 0 : position - 2;
Expand All @@ -109,8 +109,12 @@ export function Dropdown(props: Props) {
position > options.length - 3 ? options.length - 1 : position - 2;
}

const element = innerRef.current?.children[scrollPos];
element?.scrollIntoView({ block: 'nearest' });
const dropdownMenu = innerRef.current;
const element = dropdownMenu?.children[scrollPos] as HTMLElement;

if (dropdownMenu && element) {
dropdownMenu.scrollTop = element.offsetTop;
}
}

/** Update the selected value when clicking the left/right buttons */
Expand All @@ -132,7 +136,7 @@ export function Dropdown(props: Props) {
}

if (open && autoScroll) {
scrollTo(newIndex);
scrollToElement(newIndex);
}
onSelected?.(getOptionValue(options[newIndex]));
}
Expand All @@ -144,7 +148,7 @@ export function Dropdown(props: Props) {
}

if (autoScroll && selectedIndex !== NONE) {
scrollTo(selectedIndex);
scrollToElement(selectedIndex);
}

innerRef.current?.focus();
Expand Down

0 comments on commit 0957e74

Please sign in to comment.