Enter key press to next input field (Tab behaviour) #2543
-
Hey is there a default way to enable the tab behaviour for enter key or do we have to implement this manually |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Hi @sanojsilva, There is currently no way to implement this in Formik itself. You can attach an onKeyUp handler to all your inputs, and prevent |
Beta Was this translation helpful? Give feedback.
-
The accepted answer only follows the structure of the author's form.
My solution would work:
Create the function: const moveToNextInputFieldOnEnter = (event: KeyboardEvent) => {
if (event.code === "Enter") {
const currentInput = event.target as HTMLInputElement;
if (currentInput.nodeName != "INPUT") return;
const form = currentInput.form;
if (!form) return;
const formInputs = Array.from(form).filter(
(element) => element.nodeName === "INPUT"
) as HTMLInputElement[];
const nextInputIndex = formInputs.indexOf(currentInput) + 1;
if (nextInputIndex > formInputs.length) return;
const nextInput = formInputs[nextInputIndex];
nextInput.focus();
event.preventDefault();
}
}; Then add event listener in a // move to next input field on enter key press
useEffect(() => {
document.addEventListener("keydown", moveToNextInputFieldOnEnter);
return () => {
document.removeEventListener(
"keydown",
moveToNextInputFieldOnEnter
);
};
}, []); |
Beta Was this translation helpful? Give feedback.
Hi @sanojsilva,
There is currently no way to implement this in Formik itself. You can attach an onKeyUp handler to all your inputs, and prevent
event.preventDefault()
whenevent.key === 'Enter'
. You may have to useonKeyPress
in React Native, if you're using it. On textareas, you should check to make sureevent.shiftKey
is pressed, because enter normally makes a newline in textareas, while shift+enter submits.