Why do I get errors when I pass the method with () to the attribute?


#1

Question

Why do I get errors when I pass the method with () to the attribute?

Answer

Let’s take this exercise, we have a changeName method:

changeName(newName){
  this.setState({
    name: newName
  });
}

and we also have a Child component that we are passing this method to:

render() {
    return <Child name={this.state.name} onChange= { this.changeName() }/>
  }
// pay close attention  we  have () on the method  _______________^^^^

We may remember that with functions and methods from objects, having parenthesis means that we are calling them, the same principle applies here, as we pass the method as a property with the parenthesis we are calling it, so when the program gets to the render method and sees the () it will trigger that method instead of just passing it to the Child component under the onChange attribute, causing the syntax error, now, this error is from Codecademy, but when dealing with this in real life, two things may happen, either the method is triggered (since it is possible to call a method that way, but not commonly recommended) or like in this case newName would be undefined, bringing a different error. In Short, always, when passing a method to be used in another component we don’t want to call it at all:

render() {
    return <Child name={this.state.name} onChange={this.changeName}/>
  }

That way we are able to call it under the atribute name, from inside the Child component.