1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

I am new to React, so bear with me. ;)

If you use the state in the enter handler exclusively, you don’t need the state at all.

handleChangeAndEnter(event) {
  if (event.key !== 'Enter') { return; }
  this.props.theFunction(event.target.value);
}

If you use it for other things, I would recommend something like this:

handleChange(event) {
  this.setState({ value: event.target.value });
}

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

There is no need to change the state in handleEnter, because the state already reflects the current value.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.