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?