2

I'm using react-select and I added a button at the end of the MenuList component in order to load more data. When I click on this button, my state get updated and the options props of Select changes. This re-render properly the new options, however, the list is scrolled back to its top.

const MenuList = (props: MenuListProps): JSX.Element => {
  return (
    <components.MenuList {...props }>
      {props.children}
      <button onClick={fetchMore}>Load more</button>
    </components.MenuList>
  );
};

return <Select
  onFocus={onFocus}
  isLoading={loading}
  isClearable={true}
  isSearchable={true}
  options={items.map(item => {
    return { label: item.name, value: item.id };
  })}
  onInputChange={onInputChange}
  components={{ MenuList }}
/>;

So whenever I change my items state, the menu list is scrolled back to top. I tried to find a workaround by manually scrolling back to the previous position but it's visible and not satsfying.

Any ideas on how to get around this behaviour ?

rmonjo
  • 2,675
  • 5
  • 30
  • 37

1 Answers1

0

I solved this by adding react-virtuoso to the MenuList of the react-select. I used rangeChanged from Virtuoso to save the startIndex in the component state every time I got to the end of the options list and set this index as initialTopMostItemIndex in Virtuoso. It might not be the best solution but it works.

https://virtuoso.dev/virtuoso-api-reference/ -> check initialTopMostItemIndex & rangeChanged

I am also interested in other solutions.

kata
  • 43
  • 1
  • 6