Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/[email protected]/umd/react.development.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/[email protected]/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 )

like image 666
Nikita Avatar asked Dec 16 '25 19:12

Nikita


2 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.

like image 70
Nicholas Tower Avatar answered Dec 19 '25 09:12

Nicholas Tower


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.

like image 24
Adarsh Pawar Avatar answered Dec 19 '25 08:12

Adarsh Pawar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!