Reset dropdown in reactjs

Reset dropdown in ReactJs

				
					import { useState } from "react";
import "./App.css";

function App() {
  /*Ideal way to initialize at start as below */
  const [value, setValue] = useState("");

  /*Even this below code does initialize to please select at start
   not test */
  //const [value, setValue] = useState("test");

  const clearValue = () => {
    setValue({});
    /*Any of the below code works to reset the dropdown to please select
     But ideal way is to set it to ({})
    */

    //1) setValue("sdsdfsdf"); // anything
    //2) setValue("");
    //3)setValue({});
    //4)setValue("Please select");

    /*If you reset with exact same value in options in dropdownlist
      it resets with the specific type
      for example if you give Australia here 
      then on button click it resets to Australia
    */
    //setValue("Australia");
  };

  const HandleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <div className="App">
      <div>
        <select value={value} onChange={HandleChange}>
          <option value="Please select">Please select</option>
          <option value="India">India</option>
          <option value="Sri Lanka">Sri Lanka</option>
          <option value="Australia">Australia</option>
        </select>
      </div>
      <br />
      <br />
      <button onClick={clearValue}></button>
    </div>
  );
}

export default App;

				
			

Leave a Comment