Stephanie Cray
Stephanie Cray

Reputation: 13

Is there a way to get current value in React-Selects Select if the onChange event has not fired?

I have added in a React-Select component to my code where I am passing in the options prop and the onChange callback to obtain the value there. What I need to do is have the ability to reset that value back to null when the user presses a button that resets the entire form back to its original state. That is why I feel I need a way to access the current value of the select so that I could set it back to null.

I have tried to pass in ref prop to a select to get the current value there and I see in the console that currentValue and value are being set back to undefined when I choose the exit button.

                                    <Select
                                        title={'List'}
                                        options={createListOptions}
                                        ref={listSelectRef}
                                        closeMenuOnSelect={true}
                                        filterOption={createFilter({
                                            matchFrom: 'start',
                                        })}
                                        isRequired
                                        value={listId}
                                        onChange={value => {
                                            setListIds(value);
                                            setListError(false);
                                        }}
                                        error={listError}
                                    />
                                </div>```

Upvotes: 1

Views: 480

Answers (2)

Thibault Capelli
Thibault Capelli

Reputation: 208

I think you should try the AsyncSelect for this

Upvotes: 0

ravibagul91
ravibagul91

Reputation: 20765

On the click of button you can get the selected value using ref,

<Select defaultValue={options[1]} options={options} ref={this.listSelectRef}/>

<button onClick={this.getVal}>Get Value</button>

Here defaultValue is used for initial value, so that we can check without changing select value how to get already selected value.

And your function should be,

getVal = () =>{
    console.log(this.listSelectRef.current.state.value);  //this will give you selected option object
    console.log(this.listSelectRef.current.state.value.value); // this will give you value
    console.log(this.listSelectRef.current.state.value.label); //this will give you label which is actually shown on front end
}

Demo

Upvotes: 0

Related Questions