r/reactjs • u/dance2die • Jan 01 '22
Needs Help Beginner's Thread / Easy Questions (January 2022)
Happy New Year!
Hope the year is going well!
You can find previous Beginner's Threads in the wiki.
Ask about React or anything else in its ecosystem :)
Stuck making progress on your app, need a feedback?
Still Ask away! Weβre a friendly bunch π
Help us to help you better
Improve your chances of reply by
- adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- describing what you want it to do (ask yourself if it's an XY problem)
- things you've tried. (Don't just post big blocks of code!)
- Format code for legibility.
- Pay it forward by answering questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar! π
For rules and free resources~
Comment here for any ideas/suggestions to improve this thread
Thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
33
Upvotes
View all comments
Show parent comment
1
u/dance2die Jan 19 '22
Short answer is, JavaScript keeps function declarations in stack, it knows which
iis passed.Long answer.
The confusion seems to arise when
onClickin an element withinSquare,<button onClick={() => this.props.onClick()}is called.So let's backtrack from there.
A user clicks on a Square then
onClickis called.onClickis() => this.props.onClick().this.props.onClick()will refer back toonClick={() => this.handleClick(i)}withinrenderSquare(i).Within
Boardcomponent,this.renderSquare(...)is called 9 times.e.g.)
this.renderSquare(0)...this.renderSquare(8).We now know that 9 of
this.renderSquarecalls can be made when a user clicks on the board.Now let's move down back to
this.props.onClick().this.renderSquare(0)renders the top left most square.When a user clicks on it, it'd look like following (suppose that you hard-coded 0).
Now when you see
Square,this.props.onClick()will refer to() => this.handleClick(0).This will happen for other squares.
There are 9 "instances" of Squares, and each one could call
this.props.onClick(), which can be() => this.handleClick(0 to 8).JavaScript will keep each function call in stack, so React knows which
ito be used whenthis.props.onClick()is called.Please do let me know if any part is confusing (it's not edited much).