Zed
Zed

Reputation: 5931

Binding class method to this in React

I am sort of new to React and just started reading the Road to learn React free ebook. Anyway there is a part in the book where it says that in order to access this inside a class method, we need to bind class method to this. An example that is provided there clearly shows that:

class ExplainBindingsComponent extends Component {
    onClickMe() {
      console.log(this);
    }
    render() {
      return (
         <button
           onClick={this.onClickMe}
            type="button"
           >
          Click Me
        </button>
    );
  }
}

when the button is clicked, this is undefined, and if I add a constructor with this:

constructor() {
  super();
  this.onClickMe = this.onClickMe.bind(this);
}

I can access this inside a method. However, I am now confused because I'm looking at an example where there's no binding and this is accessible:

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
       list,
    };

  }

  onDismiss(id) {
    console.log(this);
    const updatedList = this.state.list.filter(item => item.objectID !== id);
    this.setState({list: updatedList});
  }

  render() {
    return (
      <div className="App">
        {this.state.list.map(item => 
             <div key={item.objectID}>
                <span>
                  <a href={item.url}>{item.title}</a>
                </span>
                <span>{item.author}</span>
                <span>{item.num_comments}</span>
                <span>{item.points}</span>
                <span>
                     <button
                         onClick={() => this.onDismiss(item.objectID)}
             type="button"
                     > 
             Dismiss
                     </button>
                </span>
              </div>
        )}
      </div>
    );
  }
}

Inside onDismiss I can print this without any problems, although I didn't bind it ? How is this different from the first example ?

Upvotes: 0

Views: 120

Answers (2)

TPHughes
TPHughes

Reputation: 1627

When you declare as a function using () => it automatically binds itself to this.

Take a look here: https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138267

Cause of these four characters:

 () =>

Thats an arrow function. Unlike regular functions, they don't have their own context (aka this) but rather take the one of their parent (render() in this case) and that has the right context.

Upvotes: 2

Related Questions