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!
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!
Share Improve this question asked Apr 30, 2021 at 3:48 chakazchakaz 3113 silver badges14 bronze badges1 Answer
Reset to default 6Sounds 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