const hello = (name) => () => {
console.log(`Hello ${name}`)
}
<button onClick={hello()}>Click Me</button>
I’m wondering why the hello
function needs to return a function?
What is the problem with:
const hello = (name) => {
console.log(`Hello ${name}`)
}
Sky020
2
It needs to, because onClick
expects a function as input.
Meaning, onClick
calls whatever you pass to it:
const myCallback = () => {};
<button onClick={myCallback}></button>
// Internally, `onClick` takes the argument, and calls it:
What is the problem with:
Nothing. This is what you should probably use. But, instead of passing the value hello()
returns, you should pass the value of hello
to onClick
.
Hope this clarifies
EDIT: Here is what React does under the hood: https://github.com/facebook/react/blob/e40893d097f6894b4768d749f796302c57161734/packages/react-devtools-timeline/src/content-views/SchedulingEventsView.js#L263-L276
1 Like
yes, this makes sense… we want onClick to run the function. Thank you!
system
Closed
4
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.