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 Components (2018) Managing State and Data Flow Update State Based on a Player's Index

Why is let index = props.index; outside of the return? Could we not use props.index within the onClick attribute?

I remember watching something about the scope, so that might be part of the answer. Would love it if someone could help refresh my memory.

2 Answers

Simon Feuster
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Simon Feuster
Full Stack JavaScript Techdegree Graduate 28,036 Points

Hi,

the answer comes a little late, but I had the same thought. You can also use props.index directly in onClick. Here is the solution (please note that I kept Counter as a class, this is the reason for the "this"):

onClick={() => this.props.changeScore(this.props.index,-1)}

Joe Elliot
Joe Elliot
5,330 Points

Yeah I wondered the same thing as it was happening. It works both ways.

I thought turning it into a variable added unnecessary code tbh but maybe it was to improve it's reusability?