Effortless Form Management in React Using Formik and Yup
Written on
Chapter 1: Introduction to Formik and Yup
Formik is a powerful library that streamlines form handling in React applications. When paired with Yup, it provides a robust solution for form validation. This article will explore how to effectively manage form inputs using Formik.
Section 1.1: Setting Up Form Validation with withFormik
To introduce validation in our form component, we can enhance it using the withFormik higher-order component. Here's an example:
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>
);
}
In the example above, we create the MyForm component to capture the necessary properties. The values object holds the input values, while touched indicates which fields have been interacted with. The errors object contains any validation errors defined in the validate method.
Section 1.2: Enhanced Validation with Yup
To simplify form validation, we can leverage the Yup library alongside Formik. Below is an example of how to implement this:
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>
);
}
In this example, we create a validation schema using Yup.object().shape(), where we define the validation criteria for the email field. The email method checks for a valid email format, and the required method ensures that the field cannot be left empty.
Chapter 2: Conclusion
By integrating Formik with Yup, we can significantly enhance our form validation process, making it both efficient and straightforward.
The first video, "React Formik Tutorial with Yup (React Form Validation)", demonstrates the integration of Formik with Yup for effective form validation.
The second video, "React Multi Step Form With Formik + Yup - React Tutorial", showcases how to create multi-step forms using Formik and Yup.