State setters for newbie ...
Hi!
Again, this is taken from codecademys react intro course.
I have the same issue as usual – reading syntax.
This code snippet is simplified as follows:
1. Why is there curly brackets around
target
in the last restructuring, but not around event
in the second restructuring. What is the curly brackets doing ...?
2. What happened to event
in the last restructuring?9 Replies
1. I'd guess they're just showing different options. All three
handleChange
functions do the same thing. Curly brackets are used to destructure variables in Javascript. The third one is saying "You're going to be passing me an argument, and I know that argument is going to have a target
attribute. I'm only interested in the target
attribute, and will take that out of the argument and pass it into my body."
2. the argument, which is called event
in the other two options, is destructured, the target
property is taken and passed into the body, and the rest of event
is discarded
The basics of destructuring are covered here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment, and Functions has a paragraph or two on it as well https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
Javascript.info also has a section https://javascript.info/destructuring-assignment#smart-function-parameters
In this case, it helps to think of the argument definition as the left side of an assignment operator, and passing of a value when calling the function as the right side. The mechanisms are the sameSo it's implicit that
handleChange
is an event listener ?that would have to be set up somewhere still, but yeah
I'm assuming it's passed to a setup function somewhere further down, but I'm not really familiar with React. For all I know it checks if a function called
handleChange
exists and just calls it when something happens
destructuring and the rest of the syntax is 100% vanilla JS thoughYes, it's passed to:
... which makes sense then.
So, cool! The take away is that destructuring needs curly braces!
Thank you, again, Jochem! 👏
as always, happy to help!
... oh, and yes ... since this is vanilla JS, I have to be careful when using React because {} is also used in JSX to insert JS.
Destructuring can be very handy, and lead to very compact but still readable code, it's a good tool to have in your toolbelt
Yes! And the more concise and precise, the better for mye brain that can only take so much syntax before I implode.
... just a quick follow up, @jochemm .
Would this further destructuring work? (can't run it since it's in the codecademy enviroment) ...
to ...
it won't go searching for matches, you have to be very specific. That second syntax will look for a
value
property on the event
you're having passed into the function, which probably doesn't exist
If you want event.target.value
you can use nested destructuring though
there's a couple examples in the Destructuring assignment MDN article I linked too