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,
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?