Formik is a library that makes form handling in React apps easy.
Yup is a library that integrates with Formik.
In this article, we’ll look at how to handle form inputs with Formik.
Validation
One way to add validation with Formik is to transform our form component into a form with validation with the withFormik
higher-order component.
For instance, we can write:
import React from "react";
import { withFormik } from "formik";
const MyForm = (props) => {
const {
values,
touched,
errors,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
name="email"
/>
{errors.email && touched.email && <div id="feedback">{errors.email}</div>}
<button type="submit">Submit</button>
</form>
);
};
const MyEnhancedForm = withFormik({
mapPropsToValues: () => ({ email: "" }),
validate: (values) => {
const errors = {};
if (!values.email) {
errors.email = "Required";
} else if (
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(values.email)
) {
errors.email = "Invalid email address";
}
return errors;
},
handleSubmit: (values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 1000);
},
displayName: "BasicForm"
})(MyForm);
export default function App() {
return (
<div className="App">
<MyEnhancedForm />
</div>
);
}
to do that.
We create the MyForm
component to get the properties we need from the props
.
values
has the inputted values.
touched
has the touched state of each input.
errors
has the form validation errors we set in the validate
method/
handleChange
has the form change handler.
handleBlur
has the blur handler.
handleSubmit
has the submit handler.
Next, we create the MyEnhancedForm
compoennt which has the validation.
mapPropsToValues
is set to a function that returns the initial values.
validate
returns an error object after checking the values from the values
parameter.
handleSubmit
has the form submit function.
values
has the form values.
setSubmitting
has a function to set the submit state of the form.
displayName
sets the displayName
property of the component for debugging.
Then we use MyEnhancedForm
in App
to render the form.
Basic Validation with Yup
To make form validation easier, we can use the Yup library to add validation to our form.
For instance, we can write:
import React from "react";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
const SignupSchema = Yup.object().shape({
email: Yup.string().email("Invalid email").required("Required")
});
export const ExampleForm = () => (
<div>
<h1>Signup</h1>
<Formik
initialValues={{
email: ""
}}
validationSchema={SignupSchema}
onSubmit={(values) => {
console.log(values);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="email" type="email" />
{errors.email && touched.email ? <div>{errors.email}</div> : null}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
export default function App() {
return (
<div className="App">
<ExampleForm />
</div>
);
}
We create the SignupSchema
with the Yup.object()
method.
We pass in an object into the shape
method to add validation to the object.
To validate strings, we call Yup.string().email()
method.
The argument of 'email'
has the validation error message.
required
makes the field required.
Then we just pass the returned object into the validationSchema
prop.
onSubmit
has the submit handler.
initialValues
has the initial values.
Then to create the Field
object, we set the name
to the property, we have in thew shape
method’s argument to apply the form validation.
touched
has the touched state of the input.
Conclusion
We can add form validation with Formik, and we can make this easier with Yup.