Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,405 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?