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 by Example Building the Application Connecting the Confirm Guests Handler

Brian DeJesus
Brian DeJesus
3,183 Points

Syntax for passing handleConfirmation function from GuestList Component to Guest component.

Why do we have to put the parenthesis-to-arrow to function handleConfirmation={() => props.toggleConfirmationAt(index)} /> in order to pass that function down to the Guest Component?

Thanks, Brian

1 Answer

Essentially, and there may be some details I am missing out on, but we need to pass the index to the toggleConfirmationAt method.

If we simply write handleConfirmation={props.toggleConfirmation(index)} the usage of our parentheses to pass an argument to the function will mean the function is immediately invoked once it is rendered, this is because we are no longer passing the function as the prop, but the result of the function once it is called.

When the toggleConfirmation function is called it calls setState which then causes the component to re-render, when the component re-renders it calls toggleConfirmation() again which then calls setState again, causing the component to re-render, causing toggleConfirmation() to be called again which calls setState() which causes.... hopefully you start to see the problem here. We get stuck in an infinite loop of the component rendering itself.

In the method used in the video we are assigning the prop to be an anonymous function, that when called will call the toggleConfirmationAt method with the parameters.

Make note that if we did not need to pass a parameter to the toggleConfirmation function, and it was able to magically know the index, we could simply write handleConfirmation={props.toggleConfirmation} and because no parameters are being passed, the parentheses are not being used, and thus the function is not called on render.

This problem is almost identical to using a function with a parameter in an event listener in regular JavaScript. This StackOverflow answer explains the same concept but in regular JavaScript with event listeners.

Szybkie Strony
Szybkie Strony
779 Points

I was just wondering about this. Thanks for the explanation Tom.