onChange vs onKeyPress for input in React 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:

&lt;input 
    type="text" 
    placeholder="Enter key words" 
    value={this.state.value}
    onChange={this.handleChange} 
    onKeyPress={this.handleEnter}
/&gt;


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.
Don't complicate your code; the first solution is just fine but needs some tweaking:
handleChange(event) {
    this.setState({value: event.target.value});
}

handleEnter(event) {
    if (event.key === 'Enter') {
        this.props.theFunction(this.state.value);
    }
}

Or, you can use what they call a guard clause and make it short and readable:
handleEnter(event) {
    if (event.key !== 'Enter') return; 
    this.props.theFunction(this.state.value);
}

And if you're using react hooks:
const handleChange = (e) =&gt; {
    setInputValue(e.target.value);
}

const handleEnter = (e) =&gt; {
    if (e.key === &quot;Enter&quot;) {
        if (value !== &quot;&quot;) {
            console.log(&quot;Hello&quot;, name);
        } 
        else {
            alert(&quot;can't pass empty string&quot;);
        }
        setInputValue(&quot;&quot;);
    }
}