InterviewHubPRO
Section Overview
Q357

Question 357 of 445

Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

80%
React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

How to bind methods or event handlers in JSX callbacks?

There are 3 possible ways to achieve this in class components:

  1. Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same rule applies for React event handlers defined as class methods. Normally we bind them in constructor.
javascript
      class User extends Component {
        constructor(props) {
          super(props);
          this.handleClick = this.handleClick.bind(this);
        }
        handleClick() {
          console.log("SingOut triggered");
        }
        render() {
          return <button onClick={this.handleClick}>SingOut</button>;
        }
      }
  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. The Create React App enables this syntax by default.
jsx
      handleClick = () => {
        console.log("SingOut triggered", this);
      };
jsx
      <button onClick={this.handleClick}>SingOut</button>
  1. Arrow functions in callbacks: It is possible to use arrow functions directly in the callbacks.
jsx
      handleClick() {
          console.log('SingOut triggered');
      }
      render() {
          return <button onClick={() => this.handleClick()}>SignOut</button>;
      }

Note: If the callback is passed as prop to child components, those components might do an extra re-rendering. In those cases, it is preferred to go with .bind() or public class fields syntax approach considering performance.