I have an input form, and when you press enter I want it to call a function. I was wondering what "the right" way of doing this is.
Right now I have an input looking like this:
<input
type="text"
placeholder="Enter key words"
value={this.state.value}
onChange={this.handleChange}
onKeyPress={this.handleEnter}
/>
And two functions that look like this
handleChange(event) {
this.setState({value: event.target.value});
}
handleEnter(event) {
if (event.key === 'Enter') {
this.setState({value: event.target.value},function(){
this.props.theFunction(this.state.value);
});
}
}
Another solution was to point both onChange and onKeyPress to the same function and write it like
handleChangeAndEnter(event) {
if (event.key === 'Enter') {
this.setState({value: event.target.value},function(){
this.props.theFunction(this.state.value);
});
} else {
this.setState({value: event.target.value});
}
}
If I remove the onChange-binding the input-field stops updating itself on input (not entirely sure why this is) and if I remove the onKeyPress-binding the event-object no longer has a key-property.
My current solution works, but it still feels like a hack.