Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between passing a function name in onclick react and calling it through callback

I want to know the difference between these two statements in react.

<Button onClick={this.Callme}></Button>

<Button onClick={()=>this.Callme()}></Button>

Its just syntax or is there any difference in functionality too.Thanks

like image 503
gANDALF Avatar asked Oct 16 '25 12:10

gANDALF


1 Answers

If the function depends on having a calling context of the instance, and the function isn't bound to the current instance already, the first code won't work, because the this inside callMe will be undefined:

class Component extends React.Component {
  name = 'component_name';
  Callme() {
    console.log(this.name);
  }
  render() {
    return (
      <button onClick={this.Callme}>Click</button>
    );
  }
}

// Render it
ReactDOM.render(
  <Component />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

The second code works, because the this in the anonymous arrow function will inherit the this from the outer scope, the instance:

class Component extends React.Component {
  name = 'component_name';
  Callme() {
    console.log(this.name);
  }
  render() {
    return (
      <button onClick={() => this.Callme()}>Click</button>
    );
  }
}

// Render it
ReactDOM.render(
  <Component />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

If the Callme method does not need to refer to the instance, then either type of onClick works.

Other solutions to this common problem include:

  • Binding the method in the constructor (this.Callme = this.Callme.bind(this))
  • Binding the method when setting the callback (onClick={this.Callme.bind(this)}>)
  • Defining the method as an arrow function in the constructor (or as a class field), rather than as a property of the prototype

    class Component extends React.Component {
      this.Callme = () => {
        console.log(this.name);
      }
    
like image 90
CertainPerformance Avatar answered Oct 19 '25 00:10

CertainPerformance