Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to call function vs function() in react onClick? [duplicate]

I'm having questions about when to call a function inside a react component. Sometimes my code breaks when I don't add the brackets to a function call, but not always. Is there some sort of rule i'm missing here?

Doesn't work

// Callback of parent component
<Link onClick={this.props.OnNavigate}>
    A link
</Link>

Does work

// Callback of parent component
<Link onClick={this.props.OnNavigate()}>
    A link
</Link>

// Callback for function of component
<li onClick={this.toggleDepartments}>other example</li>
like image 640
NealVDV Avatar asked Feb 11 '17 16:02

NealVDV


People also ask

Can you call multiple functions onClick React?

The first solution to perform multiple onClick events in React is to include all of your actions inside of a function and then call that single function from the onClick event handler. Let's explore how to do that in a React Component: import React from 'react'; function App() { function greeting() { console.

Why is React function called twice?

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.

Can onClick handle two functions?

Yes, you can call two JS Function on one onClick.

How do you beat two props onClick in React?

You could either do onClick={() => props. headlinesClicked(); props. getData()} , or extract it to a new function/method that does both calls, then invoke it with onClick={myNewMethod} or onClick={() => myNewMethod()} . Save this answer.


1 Answers

foo() is calling the function referenced by foo. foo itself is just a reference to a function, it doesn't call the function.

So, you need to use parenthesis if you want to call the function right here and now.
You have to omit the parentheses if you want to pass the function to other code so it can call the function. That would be the case with event handlers. this.props.OnNavigation should be called when the click event happens (which is some time in the future), not when the component is rendered.

like image 141
Felix Kling Avatar answered Oct 08 '22 17:10

Felix Kling