Simple auto focus to first Formik error
npm install focus-formik-errorThis component allows you to automatically focus errors in your Formik form, the focus runs after the validation.
- Support nested Arrays, nested Objects and both combined in Formik values.
- Simple and lightweight only 24kb, no extra animations.
- TypeScript support
``js`
npm i focus-formik-error
You can use it by including it inside the Formik provider or also use it with useFormik hook as follow.
Include the component inside the Formik context provider.
`tsx
import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import { ConnectedFocusError } from 'focus-formik-error'
const Basic = () => (
name: 'Poseidon',
}}
onSubmit={(values, { setSubmitting, setErrors }) => {
// Simulates server side validation
setTimeout(() => {
const errors = {} as any
if (!values.name) {
errors.country = 'Name is required'
}
setErrors(errors)
setSubmitting(false)
}, 500)
}}>
{({ errors, isSubmitting }) => (
export default Basic
`
Include the component inside you form and pass formik as props.
> NOTE: Follow the same pattern in the name attribute of the input component used in the initialValues or the focus is not going to work. I.g: name="values.name"
`tsx
import React from 'react'
import { useFormik } from 'formik'
import { FocusError } from 'focus-formik-error'
const UseFormikExample = () => {
const formik = useFormik({
initialValues: {
name: '',
},
onSubmit: (values, { setSubmitting, setErrors }) => {
setTimeout(() => {
// Simulates server side validation
const errors = {} as any
if (!values.name) {
errors.country = 'Name is required'
}
setErrors(errors)
setSubmitting(false)
}, 400)
},
})
return (
export default UseFormikExample
`
| Prop | Type | Default | Description |
| ------------ | ----------- | --------- | ------------------------------------------------------ |
| focusDelay | number (ms) | 100 | Time in ms to execute the focus in the error component |onFocus` | Function | undefined | Function, which executes after an element was focussed |
|
I actively welcome pull requests for improvements or fixes.