L
L
Leel Usama2020-10-20 18:56:53
JavaScript
Leel Usama, 2020-10-20 18:56:53

How to properly bind to this in react?

import React from 'react';
import Counter from './components/Counter';

class App extends React.Component {
  state = {
    counter: 0,
  };

  render() {
    return (
      <main>
        <h1>React Camp</h1>
        <Counter
          title='Simple counter'
          counter={this.state.counter}
          handleIncrement={this.handleIncrement}
        />
      </main>
    );
  }

// ver 1
//  handleIncrement() {
//    this.setState((state) => ({ counter: state.counter + 1 }));
//  }

// ver 2
//  handleIncrement = () =>
//    this.setState((state) => ({ counter: state.counter + 1 }));
}

export default App;


Why won't ver 1 work but ver 2 will?
Because the arrow function does not have a binding to this and the closure fires?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zhanna_K, 2020-10-20
@leelusama

because arrow functions do not contain their own this context

K
Kirill Makarov, 2020-10-20
@kirbi1996

Switch to functions, less code, convenient. Especially now there are hooks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question