Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on next field when pressing enter React.js

I would like to find a way to focus on the next field when I click enter in the input 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 have found so far, however I don't want to repeat myself by creating a function everytime I want that to happen. Is there a better and cleaner way to implement this?

like image 828
Guillermo Avatar asked Jul 25 '16 20:07

Guillermo


1 Answers

If <form> is present:

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>

CodePen

Without <form>:

function useFocusNext() {
  const controls = useRef([]);

  const handler = (event) => {
    if (event.keyCode === 13) {
      // Required if the controls can be reordered
      controls.current = controls.current
        .filter((control) => document.body.contains(control))
        .sort((a, b) =>
          a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING
            ? -1 : 1
        );

      const index = controls.current.indexOf(event.target);
      const next = controls.current[index + 1];
      next && next.focus();

      // IE 9, 10
      event.preventDefault();
    }
  };

  return useCallback((element) => {
    if (element && !controls.current.includes(element)) {
      controls.current.push(element);
      element.addEventListener('keydown', handler);
    }
  }, []);
};

...
const focusNextRef = useFocusNext();

<input ref={focusNextRef} />
<input ref={focusNextRef} />
<button ref={focusNextRef}>Submit</button>

CodePen

like image 143
Vitaly Kuznetsov Avatar answered Oct 02 '22 23:10

Vitaly Kuznetsov