Guillaume SOTTON
Guillaume SOTTON

Reputation: 67

React-select - Options are not focused on the selected value

I'm using react-select in the 3.1 version. Thanks to this library, I've done a WeekSelector component which allows user to select one specific week.

Here is my code: (simplified to illustrate important sections)

class WeekSelector extends Component {

    onSelectChange = week => {
        const { name, onChange } = this.props;

        if (onChange && week) {
            onChange(name, Number.parseInt(week.value));
        }
        else if(!week){
            onChange(name, moment().week());
        }
    };

    render() {
        const { disabled = false, id, name, value, year } = this.props;

        //Number of weeks in a year 
        const weeks = this.getWeeksDetails(year);

        //Get value
        const formattedValue = weeks.find(week => {

            if(week.value === value){
                return {
                    value: week.value,
                    label: "Week" + week.value + week.details,
                };
            }
        });

        return (
            <Select
                isClearable
                id={id}
                name={name}
                isDisabled={disabled}
                options={weeks.map(week => {
                    return {
                        value: week.value,
                        label: "Week" + week.value + week.details,
                    };
                })}
                value={formattedValue}
                onChange={this.onSelectChange}
            />
        );
    }

The problem is the following, when I select a value in options, the value is selected properly.

Week selected

But when i reopen the selector to see all the options. The selector does not focus on the selected value.

Opened options with a value selected

I seen thanks to the documentation of react-select and some online examples, that when I remove my onSelectChange function, or a setState call the value is properly selected when I reopen the options selector.

Week properly selected

I am therefore looking for a way to use my method onSelectChange and having the selector options calibrated to the chosen value.

Thank you for your attention to this issue.

Bye.

Upvotes: 2

Views: 2590

Answers (1)

Rıfat Değirmenci
Rıfat Değirmenci

Reputation: 74

add it in select

defaultValue={formattedValue}

Upvotes: 2

Related Questions