TAGS :Viewed: 3 - Published at: a few seconds ago

[ Which method of binding context in React (ES6 classes) is better ]

There is no autobinding in React ES6 classes. So developer have two options how he can to bind the context:

1) In the constructor

export class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myFunction = this.myFunction.bind(this);
  }
  myFunction() {
    // do something
  }
  render() {
    return (
      <div onClick={this.myFunction}></div>
    );
  }
}

2) Inline method

export class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  myFunction() {
    // do something
  }
  render() {
    return (
      <div onClick={this.myFunction.bind(this)}></div>
    );
  }
}

Which method is more productively working?

Answer 1


I recommend arrow function.

export class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  myFunction = (e) => {
    // e.preventDefault()
    // do something
  }
  render() {
    return (
      <div onClick={e => this.myFunction(e)}></div>
    );
  }
}

bind() is not necessary anymore.