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 trialAhmed Mahrakawy
713 PointsWhy do we pass an anonymous function to onClick={ () => props.removePlayer(props.id) }?
Why can't we just write onClick={ props.removePlayer(props.id) }?
3 Answers
Steven Parker
231,153 PointsThe anonymous function will call "removePlayer" when the event occurs.
What you are suggesting would call it immediately and store whatever it returns into "onClick".
Ahmed Mahrakawy
713 Pointsso how come we didn't add an anonymous function to the decrement or increment buttons? <button className="counter-action increment" onClick={this.incrementScore}> + </button>
Wouldn't we only want to call "incrementScore" if the onClick event is triggered?
Ahmed Mahrakawy
713 PointsAhh I see, thanks Steven!
Steven Parker
231,153 PointsSteven Parker
231,153 Points"incrementScore" (with no parentheses behind it) is a reference to a function which will be called later when the event occurs.
But "removePlayer(props.id)" (with the parentheses and argument) would call the function unless it is wrapped in a function expression (which can be anonymous).