React — onSubmit vs onClick
Anis SAFIA ? ???? ????
Software Engineer & Front-End Developer | React.js | ALX Africa Graduate | Proficient in JavaScript, TypeScript, HTML, CSS, Bootstrap, SASS, MySQL, Git, GitHub, Linux | Open to Global Opportunities
When dealing with forms, it’s usually better to use the onSubmit event handler over the onClick event handler for the button inside the form.
The reason for this is that if we we create a function to handle the onClick event handler, such as “handleClick”, then this will only get triggered when the button is clicked.
On the other hand, if the button element is inside the form, and the form itself has a handleSumbit function assigned to the onSubmit event handler, then the function will get triggered for BOTH the click on the button inside the form AND by pressing th enter ky on the keyboard, which is usually a better option.
You also need to remember to handle the default behaviour when dealing with forms, which is to pass in the event to the function, and then calling event.preventDefault() to stop the page reloading when you submit the form.
onClick for the button inside the form:
function Form() {
return (
<form className="add-form">
<h3>What do you need for your trip?</h3>
<select>
{Array.from({ length: 10 }, (_, i) => i + 1).map((el) => (
<option key={el} value={el}>
{el}
</option>
))}
</select>
<input type="text" placeholder="Items" />
<button onClick={handleClick}>Add</button>
</form>
);
}
onSubmit for the form, which covers both the button AND pressing enter:
function handleSubmit (e) {
e.preventDefault();
alert("Correct!");
}
function Form() {
return (
<form onSubmit={handleSubmit} className="add-form">
<h3>What do you need for your trip?</h3>
<select>
{Array.from({ length: 10 }, (_, i) => i + 1).map((el) => (
<option key={el} value={el}>
{el}
</option>
))}
</select>
<input type="text" placeholder="Items" />
<button>Add</button>
</form>
);
}