0

I've created a class based component in React.js in which i've only created a single input with JSX.I would like to update the state while use is writing in the input field,and there behaviour that i've not understood until now.In the code below please give attention to the implementation of my method which handles the input:

class SearchButton extends Component{
    constructor(props){
        super(props);
        this.state={
            searchTerm:""
        }
    }

    handleSearchChange(e){
        this.setState({searchTerm:e.target.value})
    }

    render(){
        return(
            <div><input value={ this.state.searchTerm } onChange={this.handleSearchChange} /><br />
            { this.state.searchTerm }
            </div>
        )
    }
}

export default SearchButton;

With the code above when i input some value in the input field i'm getting the follwing error :

bundle.js:19524 Uncaught TypeError: Cannot read property 'setState' of undefined
    at handleSearchChange (bundle.js:19524)

But when in the input handling method i replace handleSearchChange(e){this.setState({searchTerm:e.target.value})} with a fat arrow function like this handleSearchChange=(e)=>{this.setState({searchTerm:e.target.value})} everything work well.It solves my problem but i don't know why?What does the arrow function bring that is different from the first implementation?

Christian LSANGOLA
  • 2,947
  • 4
  • 22
  • 36

2 Answers2

3

When you use an arrow function, =>, the parent's this is used.

setState is party of Component thus belongs to the parent of handleSearchChange method.

When you use handleSearchChange(e){...}, this refers to the current method, thus doesn't have an access to setState.

If you are forced to use regular function syntax instead of the arrow function, then you need to bind the method in constructor.

class SearchButton extends Component{
    constructor(props){
        super(props);
        this.state={
            searchTerm:""
        }

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

    handleSearchChange(e){
        this.setState({searchTerm:e.target.value})
    }
...
dance2die
  • 35,807
  • 39
  • 131
  • 194
1

In react class component the this keyword must always refer to the class context. The normal function loses the binding of the this. arrow function does not have a this and search for the this in the upper context which is the class. check differenc explaind in details

Tarek Essam
  • 3,602
  • 2
  • 12
  • 21