ReactSelect V2 and V3 seems to have several props like clearValue
, resetValue
and setValue
. Whatever I'm trying, I'm not able to clear the selections programmatically. resetValue
seems not to be accessible from the outside.
selectRef.setValue([], 'clear') // or selectRef.clearValue()
This does not clear the current selection.
Do I miss something here or is it not fully implemented yet?
You can clear the value of react select using the ref. Just store the value in the state, and change the state programmatically using componentDidUpdate etc... Note: 'value' should be an object. A simple option would be to pass null to the value prop.
We can programmatically clear a React-Select dropdown by resetting the value that is set as the value of the value prop to null . Then the dropdown will be cleared. We have the options array with the value and label properties. value has the selection's value.
If you're using react-select you can try to pass null
to value
prop.
For example:
import React from "react"; import { render } from "react-dom"; import Select from "react-select"; class App extends React.Component { constructor(props) { super(props); const options = [ { value: "one", label: "One" }, { value: "two", label: "Two" } ]; this.state = { select: { value: options[0], // "One" as initial value for react-select options // all available options } }; } setValue = value => { this.setState(prevState => ({ select: { ...prevState.select, value } })); }; handleChange = value => { this.setValue(value); }; handleClick = () => { this.setValue(null); // here we reset value }; render() { const { select } = this.state; return ( <div> <p> <button type="button" onClick={this.handleClick}> Reset value </button> </p> <Select name="form-field-name" value={select.value} onChange={this.handleChange} options={select.options} /> </div> ); } } render(<App />, document.getElementById("root"));
Here's a working example of this.
I came across this problem myself and managed to fix it by passing a key
to the React-Select component, with the selected value appended to it. This will then force the ReactSelect
to re-render itself when the selection is updated.
I hope this helps someone.
import ReactSelect from 'react-select'; ... <ReactSelect key={`my_unique_select_key__${selected}`} value={selected || ''} ... />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With