how to bind in react functional component ? .bind(this) not working

Viewed 12825

This is not getting bound in setTimeout, where I call setState function, why is this happening?

I've added codepen bellow, I've tried same code in js, and it works

<html>
<head>
    <title></title>
    <meta charset="UTF-8" />
</head>
  <body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@16.3.1/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.3.1/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>

    <script type="text/babel">
      const state = { 
        eventCount: 0,
      }

      function setState(newState) {
        Object.assign(state, newState);
        render();
      }

      setTimeout(
        function() {
          this.setState({eventCount: 666});
        }
        .bind(this),
        1000
      );



      function App() {
        return (
          <div>
            <p>
              There have been {state.eventCount} events.
            </p>
          </div>
        )
      }


      function render() {
        ReactDOM.render(<App/>, document.getElementById('root'));
      }
      render();


    </script>
  </body>
</html>

https://codepen.io/anon/pen/gZgQWX?editors=1011 (react) https://codepen.io/anon/pen/oJZerP?editors=1111 (js example )

4 Answers

Functional components don't have state (at least not until the upcoming hooks feature). There is no setState method for you to call. In current react, if you want to use state you need to use a class component, not a functional component.

You can use the Arrow function in the place of normal function because normal function takes the global reference of this but when we use arrow function it takes the reference where it is defined. Or still, if you wanted to use the normal function you can .bind your state when you add functions or update them.

Now you're binding your function to the window context. Place the setTimeout in the App function so 'this' would be bound to the App instance.

This worked for me

function TodoItems(props) {

let getStyle = () => {
    return {
        background: '#f4f4f4',
        padding: '10px',
        borderBottom: '1px #ccc dotted',
        textDecoration: props.todo.completed ?
        'line-through' : 'none'
    }
}

function markComplete(){
    console.log(props.todo);
}

return (
    <div style={getStyle()}>
        <input type="checkbox" onChange={markComplete.bind(markComplete)} /> {' '}
        <p>{props.todo.title}</p>
    </div>
)

}

Related