Search code examples
javascriptreactjsformsdom-events

Form Submit Event gets triggered when switching to edit mode


I have a React Component that displays user data and provides an option to edit the data in place.

When I click on the edit button, the form submit action is triggered. I have marked the Edit button as type: button but this still keeps happening.

Component JSX

<form
  onSubmit={(event) => {
    event.preventDefault();
    console.log("Submit action triggered.");
  }}
>
  {isEdit ? (
    <div>
      <input type="text" defaultValue={obj.name} />
      <input type="text" defaultValue={obj.email} />
      <select defaultValue={obj.type}>
        <option value="user">User</option>
        <option value="admin">Admin</option>
      </select>
      <button type="submit">Save</button>
      <button type="reset" onClick={() => setIsEdit(false)}>
        Cancel
      </button>
    </div>
  ) : (
  <div>
    <span>{obj.name},</span>
    <span>{obj.email},</span>
    <span>{obj.type},</span>

    <button type="button" onClick={() => setIsEdit(true)}>
      Edit
    </button>
    <button type="button">Delete</button>
  </div>
  )}
</form>

Here is the link to a codesandbox example,

https://codesandbox.io/s/form-click-jz9lfd

One way I found to fix it is to put event.preventDefault() in the Edit Event handler.

My question is why is the form submit event being triggered on the edit button?


Solution

  • When you click edit button, isEdit state will be true. So button group div will be exchanged. So save button will replace the edit button because save button and edit button are at the same position of button group. Therefor, onclick event is emitted on save button too. That is the reason that submit event is emitted.

    The solution is down below. This is modified code.

    I wish you success in your studies.