JavaScript React Components Managing State and Data Flow Communicating Between Components

Stheven Cabral
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Stheven Cabral
Full Stack JavaScript Techdegree Graduate 29,833 Points

Confused about calling a component method from another component.

In this video, Guil creates the following method in the App component: handleScoreChange = (delta) => { // this.setState( prevState => ({ // score: prevState.score + 1 // })); console.log(delta); }

Then creates a prop in the Counter tag located in the Player component that passes in the handleScoreChange method: const Player = (props) => { return ( <div className="player"> <span className="player-name"> <button className="remove-player" onClick={() => props.removePlayer(props.id)}>✖</button> { props.name } </span>

  <Counter 
    score={props.score}
    index={props.index}
    changeScore={props.changeScore} 
  />
</div>

); }

Then in the Counter component, he calls the changeScore prop using an anonymous function: const Counter = (props) => { return ( <div className="counter"> <button className="counter-action decrement" onClick={() => props.changeScore(-1)}> - </button> <span className="counter-score">{ props.score }</span> <button className="counter-action increment" onClick={() => props.changeScore(1)}> + </button> </div> ); }

My question is, why do we have to use an anonymous function to call the changeScore prop? Why can't we just pass in the changeScore prop like this:

<button className="counter-action decrement" onClick={props.changeScore(-1)}> - </button>

Would like to know this as well...

2 Answers

Christopher Dehner
Christopher Dehner
10,707 Points

Parentheses are important because they are how JavaScript knows to execute a function. They're almost like a "method" (like .parseInt for strings or .map for arrays) that signals to JS that you want the function to run.

Because of this, there are a couple ways to write a callback function in onClick events (in React specifically):

  1. call the function directly without parentheses
<button onClick={ myFunction }> Call myFunction </button>

or

  1. call the function with parentheses inside of a function declaration This creates a reference for the click event instead of executing the function immediately when the JS engine runs.
<button onClick={()=>{myFunction()}}> Call myFunction </button>

Since you have to pass in the (delta) argument with parentheses, #2 is the only method that will work.

Thank you, Christopher, that's exactly what I was confused about.

Liam Clarke
MOD
Liam Clarke
Treehouse Moderator 19,837 Points

Hello

The reason its in an arrow function is so that this is bound within changeScore when you pass it as a prop.

Check this out on Reacts site explaining this behaviour

Hope this helps

Thank you for the reply, Liam. However, my issue was not with the binding but with the fact that a callback inside a callback was necessary