4

I'm studying Reactjs and have a block of code like this:

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
        
      this.state = {
         data: []
      }
    
      this.setStateHandler = this.setStateHandler.bind(this);
   };

   setStateHandler() {
      var item = "setState..."
      var myArray = this.state.data;
      myArray.push(item)
      this.setState({data: myArray})
   };

   render() {
      return (
         <div>
            <button onClick = {this.setStateHandler}>SET STATE</button>
            <h4>State Array: {this.state.data}</h4>
         </div>
      );
   }
}

export default App;

After click button, the 'SET STATE' String will appear. But i don't understand the usage of this.setStateHandler.bind(this); function. Can anybody can explain it for me?

trungducng
  • 395
  • 1
  • 7
  • 19

1 Answers1

11

this.setStateHandler().bind(this) sets the context for the function setStateHandler() to be the class object. This is necessary so that you could call this.setState({...}) inside the method, because setState() is the method of React.Component. If you do not .bind(this) you would get an error that setState() method is undefined.

Deividas
  • 6,437
  • 2
  • 26
  • 27
  • Sure, sorry about that :) still new. What's the best way to handle these questions? Do you just leave them unanswered? – Deividas Feb 24 '17 at 08:53
  • Mark it as a duplicate (as a few of us have done) and it will get closed and link to that other question, which has lots of great answers already. – caesay Feb 24 '17 at 08:54
  • Ok. Was afraid of using flag :) Do I delete my answer? – Deividas Feb 24 '17 at 08:55
  • You can leave your answer - don't flag it for moderator attention, if you don't have the reputation to mark it as a duplicate just hold on and soon you'll see a "close" button at the bottom of the question which you can use :) – caesay Feb 24 '17 at 08:56
  • 2
    I don't think that it is a duplicate question... – Ahmad Hassan Aug 26 '22 at 18:56
  • 1
    Definitely not a duplicate. The linked answer describes the basic functionality of `bind()`, but this question is specifically about `this.someFunction.bind(this);` which does not make sense for the time being (**especially** after reading the linked answer) – Andreas Fester Sep 08 '22 at 09:29
  • A very good explanation is available at https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/ – Andreas Fester Sep 08 '22 at 11:03