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

Ovidiu Cotorogea
Ovidiu Cotorogea
12,998 Points

Why access the function like that?

onClick={() => props.removePlayer(props.id)}

And why can't you access it like this ?

onClick= {props.removePlayer(props.id)}

Peter Retvari
seal-mask
.a{fill-rule:evenodd;}techdegree
Peter Retvari
Full Stack JavaScript Techdegree Student 8,392 Points

I'm not sure, just guessing but maybe for the onClick event we need a callback function, which means that one the user clicks on the button it will trigger this removeplayer method

1 Answer

Ben Wilson
Ben Wilson
4,323 Points

By adding the parenthesis at the end, you will invoke the function immediately. But wrapping this in an anonymous function, () => you can prevent this behaviour until the onClick handler is triggered.

Note that if you do not need to pass a property to your function you CAN use onClick={props.removePlayer}

But onClick={props.removePlayer()} will trigger when the component is rendered.

Hope that helps!

Ovidiu Cotorogea
Ovidiu Cotorogea
12,998 Points

Uhhh makes so much sense, thank you!