'How come a JSX element accepts a method with parenthesis vs without it as its child?
How come when I try to pass in a method without parenthesis, into a React component as a child of one of the JSX elements, I get an error in the console, but as soon as I add parenthesis, it's all fine and dandy?
For ex:
randomFunction(){
//do something here
}
This gives me an error:
<div>{this.randomFunction}</div>
But this doesn't.
<div>{this.randomFunction()}</div>
What adds to my confusion is because of the way methods are called when used as a prop. We don't use the parenthesis then.
Solution 1:[1]
this.randomFunction returns the function itself
this.randomFunction() actually calls (executes) the function
A function is not a valid JSX element, but the return from an executed function is.
So if:
function randomFunction() {
return <div><div>
}
And you call:
<div>{this.randomFunction()}<div>
The function will succeed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom |
