Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind "this" for react component method [duplicate]

I can't understand why this.click = this.click.bind(this) is needed and what is it doing.

class MyComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                name: 'Initial State'
            };
            this.click = this.click.bind(this);
        }
        click() {
            this.setState({
                name: 'React Rocks!'
            });
        }
        render() {
        return (
            <div>
            <button onClick = {this.click}>Click Me</button>
            <h1>{this.state.name}</h1>
            </div>
        );
      }
    };
like image 228
Sid24 Avatar asked Jul 17 '26 16:07

Sid24


1 Answers

If you didn't use bind(), when this.click() was called from the event listener, the value of this would not be your React component (where state and props etc. are), but instead this would be the function this.click() itself. Normally, every time a function is called, the execution context - the value of this - is set to the function itself.

Of course, that's not such a good thing if you want to access the context of your React component. bind() is one way to ensure a function runs with the same execution context of your component, giving you access to this.state, this.props etc. inside your function. Another way is to use the ES6 arrow function declaration:

let foo = () => {console.log("bar")}

Which automatically sets the value of this for foo to whatever context the function was declared in. If you declare foo in the same context as your React component, it will retain that context, thus ensuring that the value of this is the same inside of foo.

like image 50
jered Avatar answered Jul 20 '26 07:07

jered