Focus on the next field when you press Enter React.js

I would like to find a way to focus on the next field when I press Enter in the input file using React.js

@autobind handleKeyPress(event){ if(event.key === 'Enter'){ this.refs.email.focus(); } } @autobind handleKeyPressEmail(event){ if(event.key === 'Enter'){ this.refs.zip_code.focus(); } } <input onKeyPress={this.handleKeyPress} ref = 'name' /> <input onKeyPress={this.handleKeyPressEmail} ref = 'email' /> <input ref = 'zip_code' /> 

This is the best way I've found so far, however I don't want to repeat myself by creating a function every time I want it to happen. Is there a better and cleaner way to implement this?

+12
source share
4 answers

You can use componentDidMount and automatically bind links through a for-in loop.

http://codepen.io/jzmmm/pen/PzZgRX?editors=0010

  constructor() { super(); this._handleKeyPress = this._handleKeyPress.bind(this); } // Loop through the ref object, and bind each of them to onkeypress componentDidMount() { for (let x in this.refs) { this.refs[x].onkeypress = (e) => this._handleKeyPress(e, this.refs[x]); } } // This checks ENTER key (13), then checks if next node is an INPUT // Then focuses next input box _handleKeyPress(e, field) { if (e.keyCode === 13) { e.preventDefault(); // Prevent form submission if button present let next = this.refs[field.name].nextSibling; if (next && next.tagName === "INPUT") { this.refs[field.name].nextSibling.focus(); } } } render() { return ( <form> <input type="text" name="name" ref='name' /> <input type="text" name="email" ref='email' /> <input type="text" name="zip_code" ref='zip_code' /> </form> ); } 
+6
source

If the number of entries is moderate:

 function handleEnter(event) { if (event.keyCode === 13) { const form = event.target.form; const index = Array.prototype.indexOf.call(form, event.target); form.elements[index + 1].focus(); event.preventDefault(); } } ... <form> <input onKeyDown={handleEnter} /> <input onKeyDown={handleEnter} /> <input /> </form> 

Otherwise, you can wrap input in a separate component:

 function MyInput(props) { return <input onKeyDown={handleEnter} {...props} />; } 

Codepen

+4
source

Here's how I managed to make it easier:

  @autobind handleKeyPress(value, event){ if(event.key === 'Enter'){ this.refs[event].focus(); } } <input onKeyPress={(event) => this.handleKeyPress('email', event)} ref = 'name' /> <input onKeyPress={(event) => this.handleKeyPress('zip_code', event)} ref = 'email' /> <input ref = 'zip_code' /> 
0
source

In addition to Kuznetsov’s answer, if you want to lose focus without switching to the next input field, you can do this with element.blur() .

I know that Kuznetsov’s answer is appropriate, but I just want to add this for completeness.

 function handleEnter(event) { if (event.keyCode === 13) { event.target.blur() } } 
0
source

All Articles