Categories
React

How to Programmatically Clear or Reset a React-Select Dropdown?

Spread the love

React-Select is a React component that lets us render a dropdown in our React app.

In this article, we’ll look at how we can programmatically clear or reset a React-Select dropdown.

Programmatically Clear or Reset a React-Select Dropdown

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.

Conclusion

We can clear a dropdown programmatically by setting the state bound to the Select component to null .

One reply on “How to Programmatically Clear or Reset a React-Select Dropdown?”

Leave a Reply

Your email address will not be published. Required fields are marked *