Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks Form Reset dont set Select to initial value

When clicking Reset, form should go back to initial values, but the Select element goes back to first option available, have used the same method for all other form elements, and they update correctly.

Have made a Codesandbox example of the problem : https://codesandbox.io/s/lively-snowflake-tf5te

function App() {
  // Data for select dropdown box - selected is Lime
  const SelectData = ["Grapefruit", "Lime", "Coconut", "Mango"];

  // Selected Value
  const selectedValue = "Lime";

  // Set state
  const [selectBox, setSelectBox] = useState(selectedValue);

  // Submit finction
  const handleSubmit = e => {
    e.preventDefault();
    alert(`Select Selection #1: ${selectBox}`);
  };

  // Reset function
  const handleReset = () => {
    setSelectBox(selectedValue);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>
        When 'Reset' is clicked first options is selected
        <br />
        and not the state value.
      </h2>
      <form onSubmit={handleSubmit}>
        <Select
          label="Select Fruit"
          value={selectBox}
          handleChange={e => setSelectBox(e.target.value)}
          data={SelectData}
        />
        <br />
        <br />
        <input type="submit" value="Submit" />
        <input type="reset" value="Reset" onClick={handleReset} />
      </form>
      <br />
      Selectbox state value: {selectBox}
      <br />
    </div>
  );
}

Expected result, after Resetting Form, is that then Select element value is "Lime", but it is "Grapefruit".

like image 998
Flemming Krog Olsen Avatar asked Oct 15 '22 12:10

Flemming Krog Olsen


1 Answers

I changed the value to defaultValue in your DropDown.js file and it worked like charm. Check the sandbox

<select defaultValue={value} onChange={handleChange}>
            {data.map(item => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>
like image 100
Akhil Aravind Avatar answered Oct 18 '22 23:10

Akhil Aravind