Difference between onClick commands in React

Asked

Viewed 5,766 times

5

When it comes to callback functions in Reactjs, what is the difference between the options below?

  1. onClick={() => this.onFunctionCickCall()}
  2. onClick={this.onFunctionClickCall()}
  3. onClick={this.onFunctionClickCall.bind(this)}
  4. onClick={this.onFunctionClickCall}

1 answer

4


All do the same thing but some use a more current syntax.

Case 1: onClick={() => this.onFunctionClickCall()} This is the newest template to write because you don’t need to give a "fix" to the function bind within the constructor. View documentation

It is also good to say that in this case it returns a function that performs another function. Last when you need to pass some kind of parameter to the function.

Ex.:

class Foo extends Component {
  handleClick() {
    console.log('Click happened');
  }
  render() {
    return <button onClick={() => this.handleClick()}>Click Me</button>;
  }
}

You could also write like this (example below), which would have the same effect as the above case.

ex.:

class Foo extends Component {
  handleClick = () => () => {
    console.log('Click happened');
  }
  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }

Case 2 and 4: In this case it is necessary to use the "bind fix" in the constructor. View documentation. Or use Arrow Function syntax not so used but simpler to write.

In these cases if you try to use with the () at the end will run as soon as the code is loaded.

Ex.:

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('Click happened');
  }
  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

And the case 3: onClick={this.onFunctionClickCall.bind(this)}

It’s just a way to give a "bind fix" without having to put inside the constructor as used in case 2 or 4.

Of all the ways you write will be right, but some are more current/simple syntax but it’s interesting you know what’s going on behind you. This might be a good read for you to understand more

Browser other questions tagged

You are not signed in. Login or sign up in order to post.