I have the following implementation of a formik component that renders a form,
I am trying to access the first error field so I can focus on it but with no avail, i will show code
const CompanyProfile = () => {
const CompanySchema = Yup.object().shape({
name: Yup.string()
.min(2, 'too short')
.required(ERROR_REQUIRED),
industry: Yup.string().notRequired(),
address: Yup.string().notRequired(),
crn: Yup.number().required(ERROR_REQUIRED),
website: Yup.string()
.notRequired()
.min(2, 'too short'),
employeesNbr: Yup.string().required(ERROR_REQUIRED),
phoneNumber: Yup.string().required(ERROR_REQUIRED),
userRole: Yup.string().required(ERROR_REQUIRED),
personCheck: Yup.boolean().required(ERROR_REQUIRED),
});
const registerCompany = async values => {
try {
const data = values;
delete data.personCheck;
await addCompany(data);
} catch (error) {
console.log(error);
}
};
const successSubmit = values => {
registerCompany(values);
};
const forSubmit = formik => {
console.log('not valid');
const { errors } = formik;
const keys = Object.keys(errors);
console.log(formik);
if (keys.length > 0) {
const selector = `[id="${keys[0]}"]`;
const errorElement = document.getElementsByName(selector);
errorElement.focus();
}
};
const formik = useFormik({
initialTouched: false,
validateOnChange: true,
validateOnBlur: true,
initialValues: {
name: '',
industry: '',
address: '',
crn: '',
website: '',
employeesNbr: '',
phoneNumber: '',
userRole: '',
personCheck: false,
},
validationSchema: CompanySchema,
onSubmit: values => {
successSubmit(values);
},
handleSubmit: formik => {
forSubmit(formik);
},
});
return (
<Skeleton pageTitle={PAGE_TITLE_COMPANY_PROFILE}>
<CompanyProfileForm formik={formik} />
</Skeleton>
);
};
export default connect(CompanyProfile);
I dont know where I am going wrong, I attached the name,value, onchange correctly in the input fields because I am able to extract the values
Thank you
Focus Formik error
This component allows you to automatically focus errors in your Formik form, the focus runs after the validation.
Main goals
- Support nested Arrays, nested Objects and both combined in Formik values.
- Simple and lightweight only 24kb, no extra animations.
- TypeScript support
Getting Started
npm i focus-formik-error
How to use it
You can use it by including it inside the Formik provider or also use it with useFormik hook as follow.
With Formik provider
Include the <ConnectedFocusError />
component inside the Formik context provider.
import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import { ConnectedFocusError } from 'focus-formik-error'
const Basic = () => (
<Formik
initialValues={{
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 }) => (
<Form className={'form'}>
<ConnectedFocusError />
<div className={'input-container'}>
<label>Name </label>
<Field
type='text'
name='name'
className={`input ${errors.name ? 'input-error' : ''}`}
/>
<ErrorMessage name='name' component='div' className={'error-text'} />
</div>
<button
type='submit'
disabled={isSubmitting}
style={{ marginBottom: '5em' }}>
{isSubmitting ? 'Submitting' : 'Submit'}
</button>
</Form>
)}
</Formik>
)
export default Basic
With useFormik
Include the <FocusError />
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"
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 (
<form onSubmit={formik.handleSubmit}>
<FocusError formik={formik} />
<input
id='values.name'
name='values.name'
type='text'
onChange={formik.handleChange}
value={formik.values.name}
/>
{formik.errors.name}
<button type='submit' disabled={formik.isSubmitting}>
Submit
</button>
</form>
)
}
export default UseFormikExample
Options
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 |
Contribute
I actively welcome pull requests for improvements or fixes.
License
MIT License
<ErrorMessage />
is a component that renders the error message of a given field if that field has been visited (i.e.touched[name] === true
) (and there is an error
message present). It expects that all error messages are stored for a given field as a string. Like <Field />
, <FastField />
, and <FieldArray />
, lodash-like dot path and bracket syntax is supported.
Example
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from "yup";
const SignupSchema = Yup.object().shape({
name: Yup.string()
.min(2, 'Too Short!')
.max(70, 'Too Long!')
.required('Required'),
email: Yup.string()
.email('Invalid email')
.required('Required'),
});
export const ValidationSchemaExample = () => (
<div>
<h1>Signup</h1>
<Formik
initialValues={{
name: '',
email: '',
}}
validationSchema={SignupSchema}
onSubmit={values => {
// same shape as initial values
console.log(values);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="name" />
- {errors.name && touched.name ? (
- <div>{errors.name}</div>
- ) : null}
+ <ErrorMessage name="name" />
<Field name="email" type="email" />
- {errors.email && touched.email ? (
- <div>{errors.email}</div>
- ) : null}
+ <ErrorMessage name="email" />
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
Props
Reference
Props
children
children?: ((message: string) => React.ReactNode)
A function that returns a valid React element. Will only be called when the field has been touched and an error exists.
<ErrorMessage name="email">{msg => <div>{msg}</div>}</ErrorMessage>
component
component?: string | React.ComponentType<FieldProps>
Either a React component or the name of an HTML element to render. If not specified, <ErrorMessage>
will just return a string.
<ErrorMessage component="div" name="email" />
<ErrorMessage component="span" name="email" />
<ErrorMessage component={Custom} name="email" />
<ErrorMessage name="email" />
name
name: string
Required
A field’s name in Formik state. To access nested objects or arrays, name can also accept lodash-like dot path like social.facebook
or friends[0].firstName
render
render?: (error: string) => React.ReactNode
A function that returns a valid React element. Will only be called when the field has been touched and an error exists.
<ErrorMessage name="email" render={msg => <div>{msg}</div>} />
Subscribe to our newsletter
The latest Formik news, articles, and resources, sent to your inbox.
Copyright © 2020 Formium, Inc. All rights reserved.
Примеры кода
фокус ошибки formik
export default class ScrollToError extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.submitCount !== this.props.submitCount && !this.props.isValid) {
if (Object.keys(this.props.errors)[0] === this.props.name) {
ReactDOM.findDOMNode(this.props.inputRef.current).scrollIntoView({ behavior: 'smooth' });
}
}
}
render() {
return null;
}
}
Похожие страницы
Похожие страницы с примерами
На других языках
Эта страница на других языках
empty row
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
Популярное в этой категории
Популярные страницы с примерами в категории
empty row