How to bind methods or event handlers in JSX callbacks in react.js?

Answer

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.
2) 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.
3)Arrow functions in callbacks: You can use arrow functions directly in the callbacks.

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>;
}

All react js Questions

Ask your interview questions on react-js

Write Your comment or Questions if you want the answers on react-js from react-js Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---