Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics (retired) Designing Data Flow Communicating Events

Nadia Stoffel
Nadia Stoffel
2,964 Points

onChange & onScoreChange

can you explain in more detail why we can't just call props.onChange(-1) on the Counter's onclick event, why we need it wrapped in an anonymous function?

and also,

how does the Player component receive the actual argument of Counter's onChange's -1 or 1. Where specifically is that number being stored?

3 Answers

Seth Kroger
Seth Kroger
56,413 Points

To answer the first: You can't pass any argument to the function using onClick, so you need to wrap it inside an anonymous function do to so.

Well, more precisely you can't pass your own arguments because onClick passes the its function an Event object with information of the click event. When we write onClick={function() {props.onChange(-1);} we really mean onClick={function(event) {props.onChange(-1);} It's just that the details of the event beyond the button being clicked are irrelevant here so we ignore it. Writing onClick={props.onChange(-1)} is nonsensical (and locks up Firefox with a Unresponsive Script error if you try it).

For your second question: The Player does not receive the arguments. The Application receive them. What the Player does is forwarding the callback from Application (Application.onScoreChange) to the Counter component. When Counter's onChange is trigger, it passes 1 or -1 directly to Application.onScoreChange. Every data here is stored in Application.

Nadia Stoffel
Nadia Stoffel
2,964 Points

i kind of get it, but i think what solved this in my understanding is:

a react expression evaluates before being sent to the onClick property.

so without the anonymous function, props.onChange(1) would evaluate to undefined and be sent like that to onClick. Instead, we need to send the whole function to keep it from trying to execute too early.

This post says it better: http://stackoverflow.com/questions/24050456/onclick-assigned-function-with-parameters

Anyone to answer my second question?