I am currently working on a Youtube tutorial of react todo list by web dev simplifed link source codes
In the NewToForm.jsx form, there is a form with onSubmit handler
<form onSubmit={handleSubmit} className="new-item-form">
<div className="form-row">
<label htmlFor="item">New Item</label>
<input
value={newItem}
onChange={e => setNewItem(e.target.value)}
type="text"
id="item"
/>
</div>
<button className="btn">Add</button>
</form>
function handleSubmit(e) {
e.preventDefault()
if (newItem === "") return
onSubmit(newItem)
setNewItem("")
}
In the code, the value of onSubmit equals handleSubmit, which is a function that changes value of some states.
But as I know, an arrow function is needed to wrap the event handler, otherwise react keeps re-render for infinite number of times.
Why it is necessary to use Arrow functions with React Event handler | by kirill ibrahim | Dev Genius
So I want to ask why the event handler of submit is different from those of click and change? Is there any special about the handleSubmit function? Thank you!
The onSubmit
of form
is not different to any events of other elements.
In Javascript, a function
is a first-class object, meaning, they can be assigned to a variable and pass around. Similar to how we pass around string or integer in a variable.
Now in this line:
<form onSubmit={handleSubmit} className="new-item-form">
We are technically setting the onSubmit
function of form to our handleSubmit
. One thing to take note is we are only assigning the handleSubmit
to the onSubmit
that's why this works.
Now on the article you linked, it shows something like this:
<form onSubmit={handleSubmit()} className="new-item-form">
The key difference is this time, it's onSubmit={handleSubmit()}
. It's not an assignment anymore. Once we added that ()
, it's already a function call and the handleSubmit
is invoked. That's also why during each render, it is already called right away.
If we insist on doing the onSubmit={handleSubmit()}
way, we have to put it in an arrow function so it's not a function call anymore but now, a definition of function to be called (it's an assignment again). Something like this:
<form onSubmit={() => handleSubmit()} className="new-item-form">
If we don't have params on the function, we could just stick with onSubmit={handleSubmit}
for simpler syntax but if we do have params, we can't really pass it since once we add that ()
it will become a function call. Hence, we have the arrow function syntax to help us with this like this:
<form onSubmit={() => handleSubmit(name)} className="new-item-form">