this Context

suggest change

Using React.createClass will automatically bind this context (values) correctly, but that is not the case when using ES6 classes.

React.createClass

Note the onClick declaration with the this.handleClick method bound. When this method gets called React will apply the right execution context to the handleClick.

import React from 'react';

const MyComponent = React.createClass({
  handleClick() {
    console.log(this); // the React Component instance
  },
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }
});

export default MyComponent;

React.Component

With ES6 classes, methods are not automatically bound to the component instance. If you pass this.handleClick as a callback, this is undefined when it runs (strict mode), not the component.

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  handleClick() {
    console.log(this); // undefined
  }
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }
}

export default MyComponent;

There are a few ways we could bind the right this context.

Case 1: Bind inline:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  handleClick() {
    console.log(this); // the React Component instance
  }
  render() {
    return (
      <div onClick={this.handleClick.bind(this)}></div>
    );
  }
}

export default MyComponent;

Case 2: Bind in the class constructor

Another approach is changing the context of this.handleClick inside the constructor. This way we avoid inline repetition. Considered by many as a better approach that avoids touching JSX at all:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log(this); // the React Component instance
  }
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }
}

export default MyComponent;

Case 3: Use an arrow function as a class property

You can also use an arrow function as a class field so you do not bind explicitly. Class fields are not ES6; they need a transpiler such as Babel’s class-properties plugin:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  handleClick = () => {
    console.log(this); // the React Component instance
  }
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }
}

export default MyComponent;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents