Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to bind this keyword to an event handler in react?

So, let's say I have a class named Search that is a simple input field with a submit button. Here's the code for that.

class Search extends Component {
    constructor(props){
        super(props);
        this.state = {term: ''};

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {
        console.log(this);
        console.log(e.target.value);
        this.setState({term: e.target.value});
    }

    render() {
        return (
                <form className='input-group'>
                    <input className='form-control' 
                    placeholder='City' 
                    onChange={this.handleChange}
                    value={this.state.value}/>
                    <span className='input-group-btn'>
                        <button type='submit' className='btn btn-primary'>Submit</button>
                    </span>
                </form>
        )
    }
}

So, I need to bind the this keyword to the event handler, handleChange, inside the constructor of the class so that it has the correct reference to this inside the handleChange event handler.

However, if I change the code to the following

class Search extends Component {
    constructor(props){
        super(props);
        this.state = {term: ''};

        //this.handleChange = this.handleChange.bind(this);

Line comment above

    }

    handleChange(e) {
        console.log(this);
        console.log(e.target.value);
        this.setState({term: e.target.value});
    }

    render() {
        return (
                <form className='input-group'>
                    <input className='form-control' 
                    placeholder='City' 
                    onChange={(e) => this.handleChange(e)} 

Line change above

                    value={this.state.value}/>
                    <span className='input-group-btn'>
                        <button type='submit' className='btn btn-primary'>Submit</button>
                    </span>
                </form>
        )
    }
}

Now, if I change the code to the above, I no longer need to do that because I am calling this.handleChange from inside of a callback. Why is this the case?

like image 825
random_coder_101 Avatar asked Mar 11 '23 15:03

random_coder_101


1 Answers

The reason is that you use an arrow function when you create the callback.

You don't need to bind arrow functions to this, because arrow functions "lexically binds the this value".

If you want, you can change your event handler functions into arrow functions, so that you don't need to bind them. You may need to add the babel plugin 'transform-class-properties' to transpile classes with arrow functions.

If you want to change handleChange into an arrow function, simply change

handleChange(e) {
    ...
}

to

handleChange = (e) => {
    ...
}
like image 183
ArneHugo Avatar answered Mar 20 '23 13:03

ArneHugo