Reputation: 616
What is the difference between
onChange={({ target: { value } }) => setInsertedTitle(value)}
and
onChange={setInsertedTitle}
When should one or another be used?
Upvotes: 2
Views: 4617
Reputation: 355
Using onChange={({ target: { value } }) => setInsertedTitle(value)}
you are passing the current target value as a parameter.
It is because onChange generates an Event, and you access the value by event.target.value ...
event: {
target: {
value: "string"
}
}
On the other hand, when you use the function like in onChange={setInsertedTitle}, it receives the event.
You can see it here: https://codesandbox.io/s/compassionate-fast-krrib?file=/src/App.js
Upvotes: 5
Reputation: 8718
Look at what each does and spot the differences:
onChange={({ target: { value } }) => setInsertedTitle(value)}
func
)onChange
/func
gets called, e.g. func(event)
:
value
to the value of event.target.value
setInsertedTitle
with value
(therefore event.target.value
)In the other case:
onChange={setInsertedTitle}
When onChange
gets called with event
, we directly call setInsertedTitle
with event
.
Therefore the main difference is whether it passes event.target.value
or just event
.
Upvotes: 4
Reputation: 1075895
The first one passes a function to onChange
that, when called, will get the value
of the target
element of the event (this is probably an input
element, so target
will be that input
element) and pass that value to setInsertedTitle
. So when the event occurs, setInsertedTitle
gets called with a string (the value of the input).
The second one will directly pass setInsertedTitle
to onChange
. When the event occurs, setInsertedTitle
will get called with an event object rather than the value of the input.
For the avoidance of doubt: The first one is correct, the second one is incorrect. (Even if you wanted to have an event object in your state data — which you almost certainly don't — you can't just keep the one you're passed; you're not allowed to keep them as they get reused [I think that's going to change at some point].)
Upvotes: 2