React <input>: Dismiss soft keyboard on enter

Viewed 1115

I'm writing a React app that will be used on mobile devices.

One of the pages has an <input> text that the user inputs with the keyboard. Entering text in the field has an immediate effect, and thus no button needs to be pushed afterwards. I'd like to have the soft keyboard 'enter' key simply dismiss the keyboard without taking any action. Is this at all possible? It sounds so simple, yet I couldn't find how to do it.

For what it's worth, I tried adding enterKeyHint="done" attribute (as described here), but other than changing the enter title from 'done' to a 'v' sign it does not dismiss the keyboard.

Any ideas? Thanks in advance!

1 Answers

Sounds like it's simply a matter of triggering blur() from the element itself. You could either trigger blur() from the event handler or by using useRef.

Make sure to e.stopPropagation() or e.preventDefault() if you don't want your input to bubble the event upwards, or if it's inside of a form

export default function App() {
  const onEnter = (e) => {
    if (e.key === "Enter") {
      e.target.blur();
    }
  };

  return (
    <div className="App">
      <input onKeyUp={onEnter} />
    </div>
  );
}

Demo: https://codesandbox.io/s/relaxed-antonelli-j6c5d?file=/src/App.js

Related