Skip to content

fix Submit button behaves differently than enter key submission, at least for step validation #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions packages/formik/src/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,27 @@ export const Form = React.forwardRef<HTMLFormElement, FormProps>(
const { action, ...rest } = props;
const _action = action ?? '#';
const { handleReset, handleSubmit } = useFormikContext();

// Create a custom onSubmit handler that ensures form validation
// is triggered the same way for both button clicks and enter key submissions
const onSubmit = React.useCallback(
(e: React.FormEvent<HTMLFormElement>) => {
if (e && e.preventDefault && typeof e.preventDefault === 'function') {
e.preventDefault();
}

if (e && e.stopPropagation && typeof e.stopPropagation === 'function') {
e.stopPropagation();
}

return handleSubmit(e);
},
[handleSubmit]
);

return (
<form
onSubmit={handleSubmit}
onSubmit={onSubmit}
ref={ref}
onReset={handleReset}
action={_action}
Expand All @@ -31,4 +49,4 @@ export const Form = React.forwardRef<HTMLFormElement, FormProps>(
}
);

Form.displayName = 'Form';
Form.displayName = 'Form';