Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Showing selected option on top view #4305

Closed
hyphen1370 opened this issue Dec 2, 2020 · 3 comments
Closed

Showing selected option on top view #4305

hyphen1370 opened this issue Dec 2, 2020 · 3 comments
Labels
issue/reviewed Issue has recently been reviewed (mid-2020)

Comments

@hyphen1370
Copy link

Hello,

I am using the latest version of react-select. I am seeing default behavior to show the selected option at the buttom of the menu view like this
image

Is there any way to change so that when the menu is open, "Cape Verde" shows where the "Brunei Darussalam" shows in the picture?

Thanks

@bladey bladey added category/question issue/reviewed Issue has recently been reviewed (mid-2020) labels Dec 2, 2020
@ebonow
Copy link
Collaborator

ebonow commented Dec 7, 2020

You can add an onMenuOpen prop and automatically scroll the focused option to the top.

  const selectRef = useRef();

  const onMenuOpen = () => {
    setTimeout(() => {
      const { focusedOptionRef } = selectRef.current.select;
      focusedOptionRef && focusedOptionRef.scrollIntoView();
     }, 1);
  };

  return <Select ref={selectRef} onMenuOption={onMenuOption} />

Demo: codesandbox

A couple notes about this...

  • It's a known issue that the focusMenuRef and menuListRef are not immediately available at the time of onMenuOpen, so you will need a brief setTimeout to add it to the event queue to be called after render. "menuListRef" is null when referenced in onMenuOpen #4243

  • There can be a sudden jump in the changing of it being moved to the top, so there maybe a possibility of adjusting the opacity/visibility before and after it happens if you want by accessing the selectRef.current.select.menuListRef.

In any case, this should resolve your use case. If you have any further questions, happy to discuss.

@gino
Copy link

gino commented Mar 4, 2023

Is there already a better recommended way to achieve this? I would also like to display the selected item as the first option, isn't there a way to invoke the scrollIntoView function that is being used under the hood?

scrollIntoView({ block: "start", inline: "start" })

@Devalekarthik
Copy link

Is there any way to stop sudden jump in the changing of it being moved to the top..?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
issue/reviewed Issue has recently been reviewed (mid-2020)
Projects
None yet
Development

No branches or pull requests

5 participants