I currently learnign React. I was introduced to a problem with "this" keyword. Basically i understand how it works but in react or maybe in ES6 class i m finding my self confused. For example i have the below class SearchBar with a method onFormSubmit. If i try to console.log(this.state.term) inside this method it will throw an error of undefined property. I know how to solve this error (arrow functions,bind,etc.) and that is not my problem. My problem is that i dont understand why it is not working on OnFormSubmit() method but it will work if i console.log(this.state.term) in render() method.
import React from 'react';
class SearchBar extends React.Component {
state = {term: ''};
onFormSubmit(e) {
e.preventDefault();
console.log(this.state.term); //here is the error "cannot read of undefined property"
}
render() {
return(
<div className="ui segment">
<form onSubmit={this.onFormSubmit} className="ui form">
<div className="field">
<label>Image Search</label>
<input
type="text"
value={this.state.term}
onChange={(e) => this.setState({term: e.target.value})}
/>
</div>
</form>
</div>
);
}
}
export default SearchBar;