React: is there way to bind this to multiple methods in a component?

So my current class component owns 5 methods(and expanding) and ive bound all in the constructor using bind(this), but this just makes the code so lengthy. Im aware one way to avoid this is use arrow functions inside child components events. Is there way to instead use a shorter code in the parent constructor, like sifting thru all custom made methods and bind this to them(use a loop or something)?

Here are examples from React docs on how to get around this:

Experimental public class syntax:

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

Arrow function in the callback:

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}

Lastly, you can use React Hooks :smiley:

1 Like