Bind onChange function with context of the component
If we have a component like this
import React, {Component} from 'react'
export default class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {term: ''};
}
onInputChange(event) {
console.log(event.target.value)
this.setState({term: event.target.value})
}
render() {
return (
<from className="input-group">
<input
placeholder="Get a five-day forecast in your favourite cities."
className="form-control"
value={this.state.term}
onChange={this.onInputChange}/>
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">Submit</button>
</span>
</from>
);
};
}
where we are trying to change the state, when we just entering something into the input, we are going to get Undefined State error.
Why is this?
Because the function onInputChange is not binded to the component. It is a mystery-context. So, we should bind it, and it's easy:
...
constructor(props) {
super(props);
this.state = {term: ''};
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
console.log(event.target.value);
this.setState({term: event.target.value});
}
...
We are just replacing this function with binded one.