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.
For instance, we can write:
import { useState } from "react";
import Select from "react-select";
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two" }
];
export default function App() {
const [value, setValue] = useState("one");
const handleChange = (value) => {
setValue(value);
};
return (
<div className="App">
<Select
name="form-field-name"
value={value}
onChange={handleChange}
options={options}
/>
<button onClick={() => setValue(null)}>reset</button>
</div>
);
}
We have the options
array with the value
and label
properties.
value
has the selection’s value.
label
is the value displayed to the user.
The value
state is set as the value of the value
prop.
Then we have the handleChange
function that takes the value
parameter and call setValue
to change the value of value
.
We set the onChange
prop to the handleChange
function so that we can set the value of value
.
The options
prop is set to the options
array.
We have a button to call setValue
with null
to clear the dropdown value.
2 replies on “How to Programmatically Clear or Reset a React-Select Dropdown?”
this worked!
Appreciate the blog , but the blog title read ,”how to programmatically reset” . I believe that conveys , when the react dropdown has a value and if the user changes the value and now i need to go back to previously selected value without changing the react select again , is there any way we can achieve this ?