How to properly bind to this in react?

  • 0
    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 doesn't ver 1 work and ver 2 work?
    Is it because the arrow function has no binding to this and the closure is triggered?
    JavaScript Julian Blake, Dec 15, 2020

  • 2 Answers
  • 0
    because arrow functions do not contain their own this context
    Anonymous

  • 0
    Move to functions, less code, convenient. Moreover, there are now hooks.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!