@@ -45,7 +45,7 @@ const NonFieldErrors: FC<NonFieldErrorsProps> = ({
45
45
}
46
46
47
47
export type FormErrors < Values > = FormikErrors <
48
- Omit < Values , "non_field_errors " > & { non_field_errors : string }
48
+ Omit < Values , "__all__ " > & { __all__ : string }
49
49
>
50
50
51
51
type _FormikProps < Values > = Omit < FormikProps < Values > , "errors" > & {
@@ -56,43 +56,45 @@ type BaseFormProps<Values> = Omit<FormikConfig<Values>, "children"> & {
56
56
children : ReactNode | ( ( props : _FormikProps < Values > ) => ReactNode )
57
57
scrollIntoViewOptions ?: ScrollIntoViewOptions
58
58
nonFieldErrorsProps ?: Omit < NonFieldErrorsProps , "children" >
59
- order ?: Array < { name : string ; inputRef : RefObject < HTMLInputElement > } >
59
+ fieldRefs ?: Array < { name : string ; inputRef : RefObject < HTMLInputElement > } >
60
60
}
61
61
62
62
const BaseForm = < Values extends FormValues > ( {
63
63
children,
64
64
scrollIntoViewOptions = SCROLL_INTO_VIEW_OPTIONS ,
65
65
nonFieldErrorsProps,
66
- order ,
66
+ fieldRefs = [ ] ,
67
67
...otherFormikProps
68
68
} : BaseFormProps < Values > ) => (
69
69
< Formik { ...otherFormikProps } >
70
70
{ /* @ts -expect-error */ }
71
71
{ ( formik : _FormikProps < Values > ) => {
72
- let nonFieldErrors : undefined | JSX . Element = undefined
73
- if ( Object . keys ( formik . errors ) . length ) {
74
- if ( typeof formik . errors . non_field_errors === "string" ) {
75
- nonFieldErrors = (
76
- < NonFieldErrors { ...nonFieldErrorsProps } >
77
- { formik . errors . non_field_errors }
78
- </ NonFieldErrors >
79
- )
80
- } else if ( order && order . length ) {
81
- const errorNames = getKeyPaths ( formik . errors )
82
-
83
- const inputRef = order . find ( ( { name } ) =>
84
- errorNames . includes ( name ) ,
85
- ) ?. inputRef
86
-
87
- if ( inputRef ?. current ) {
88
- inputRef . current . scrollIntoView ( scrollIntoViewOptions )
89
- }
90
- }
72
+ const hasErrors = Boolean ( Object . keys ( formik . errors ) . length )
73
+ const hasNonFieldErrors =
74
+ hasErrors && typeof formik . errors . __all__ === "string"
75
+
76
+ // If a submission was attempted and refs to the fields were provided.
77
+ if (
78
+ hasErrors &&
79
+ ! hasNonFieldErrors &&
80
+ formik . isSubmitting &&
81
+ fieldRefs . length
82
+ ) {
83
+ const errorNames = getKeyPaths ( formik . errors )
84
+
85
+ const input = fieldRefs . find ( ( { name } ) => errorNames . includes ( name ) )
86
+ ?. inputRef . current
87
+
88
+ if ( input ) input . scrollIntoView ( scrollIntoViewOptions )
91
89
}
92
90
93
91
return (
94
92
< >
95
- { nonFieldErrors }
93
+ { hasNonFieldErrors && (
94
+ < NonFieldErrors { ...nonFieldErrorsProps } >
95
+ { formik . errors . __all__ as string }
96
+ </ NonFieldErrors >
97
+ ) }
96
98
< FormikForm >
97
99
{ typeof children === "function" ? children ( formik ) : children }
98
100
</ FormikForm >
0 commit comments