Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening the menu to the default value in react-select

I am using react-select to allow the user to choose their birth year. If the user has already filled it in, it will be preset to some value, e.g. 1950. The input shows the correct value, however when the menu is opened it is scrolled to the top and shows the most recent years (2018, 2017, 2016, etc).

How do I get it to scroll down to 1950 and highlight that item by default?

My code:

class YearPicker extends React.PureComponent {
    options = [
        {label: 2018, value: 2018},
        {label: 2017, value: 2017},
        // ...
        {label: 1950, value: 1950},
        {label: 1949, value: 1949},
        // ...
    ]

    render () {
        return (
            <Select
                options={this.options}
                value={this.props.value}
            />
        )
    }
}

CodeSandbox—this should default to 2002. Once you select a value (2002 or otherwise) it works fine, but when the page first loads you have to scroll down within the menu to find the value.

Per the docs I have tried value and defaultValue as well as selectedOption but nothing seems to work. I created a very hacky workaround by leveraging onMenuOpen to find the correct DOM element after it's rendered and then scroll to it, however this breaks the functionality of the arrow keys.

like image 994
craigpatik Avatar asked Mar 01 '26 08:03

craigpatik


2 Answers

I looked at their source code and actually, you are doing everything right. The issue is in the following line of their code in Select.js:

 const selectedIndex = menuOptions.focusable.indexOf(selectValue[0]);

Here they are determining the index of the default option using indexOf and comparing objects. Object equality is performed by reference and not by value. So when you initialize the component for the first time and you explicitly provide an object, the equality fails. Wrong option is highlighted only for the first time. Rest of the times, object equality works since they extract the selected object out of the options and indexOf works

Check the working fork https://codesandbox.io/s/0xzmy6wvln

What I have done is created a function that extracts the selected option from the options array and passes that and so the equality works even for the first time.

I would encourage you to raise this issue on their repo and try to get it fixed.

like image 116
cdoshi Avatar answered Mar 03 '26 20:03

cdoshi


Set the default value to the object from the options menu.

<Select
    options={this.options}
    defaultValue={this.options.find(option => option.value === this.props.value)}
/>

This is a workaround for the bug that @cdoshi described.

like image 43
arsent Avatar answered Mar 03 '26 21:03

arsent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!