What happens if we pass the function with parentheses?

Question

In the context of this exercise, what happens if we pass the function with parentheses?

Answer

Say that you passed in a function with parentheses after the function name as a prop, like the following,

render() {
  return <Button press={this.press()}/>
}

This will call the press() function, and then the value passed as the prop will actually be the return value of the function rather than the function itself. By default, functions return undefined. As a result, when passing a function as a prop, there must not be any parentheses following its name.

The correct way to pass the function to the component would be,

render() {
  return <Button press={this.press}/>
}
14 Likes

How would we pass a function or method that has parameters without using the parentheses?

5 Likes

You can pass the parameters as distinct props as well. Then in the component that you’ve passed the props, you can combine all of them to invoke the function call.

9 Likes

Alternatively, you could pass a parameterless arrow function that passes the arguments for you:

render() {
  return <Button press={() => {this.press(arguments)}}/> 
}
21 Likes