React.js
Angular
Ethical Hacking
Agile
AWS
BlockChain
Cassandra
Cloud
Salesforce
Scaled Agile
TOGAF
DevOps
GIT
Jenkins
Jira
Kibana
Linux
NGINX
Ansible
Artificial Intelligence
in React JS by

How to bind methods or event handlers in JSX callbacks?

Click here to read more about React JS

1 Answer

0 votes
by

There are 3 possible ways to achieve this:

  1. Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same thing applies for React event handlers defined as class methods. Normally we bind them in constructor.
class Component extends React.Componenet {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    // ...
  }
}

  1. Public class fields syntax: If you don't like to use bind approach then public class fields syntax can be used to correctly bind callbacks.
handleClick = () => {
  console.log('this is:', this)
}
<button onClick={this.handleClick}>
  {'Click me'}
</button>
  1. Arrow functions in callbacks: You can use arrow functions directly in the callbacks.
<button onClick={(event) => this.handleClick(event)}>
  {'Click me'}
</button>

Related questions

Madanswer
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Jun 19 in React JS by JackTerrance
...