You get a bonus - 1 coin for daily activity. Now you have 1 coin

How do you bind methods or event handlers in JSX callbacks in REACT?

Practice



There are 3 possible ways to achieve this:

  1. Binding in the constructor: in JavaScript classes, methods are not bound by default. The same applies to React event handlers defined as class methods. Normally we bind them in the 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 using the binding approach, then to bind callbacks correctly you can use the public class fields syntax .
handleClick = () => {
  console.log('this is:', this)
}
  {'Click me'}
  1. Arrow functions in callbacks: you can use arrow functions directly in callbacks.
 this.handleClick(event)}>
  {'Click me'}
Note. If the callback is passed as a prop to child components, those components may perform an extra re-render. In such cases it is preferable to go with the .bind()

or public class fields syntax approach for performance reasons.

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone