Handling forms in React can get tricky, especially when managing complex states and validation. Formik is a popular library that simplifies this by managing form states, validations, and submissions with ease. In this guide, we’ll explore how to set up a basic form using Formik.
What is Formik?
Formik is a small library for React forms. It helps manage form state and validation, making it easier to build reliable and maintainable forms. By using Formik, you can handle complex form logic without cluttering your components with state management code.
Setting Up Formik : First, install Formik in your project:
npm install formik
Then, import Formik and the necessary components in your file:
import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; // for validation
Creating a Simple Form
Let’s create a simple sign-up form with fields for Name, Email, and Password.
Step 1: Set up Formik with Initial Values
Define the initial values for the form fields using the initialValues prop in the Formik component:
<Formik initialValues={{ name: '', email: '', password: '' }}>
Step 2: Add Validation with Yup
Yup is a validation library commonly used with Formik. You can define a validation schema for your form fields using Yup:
const validationSchema = Yup.object({ name: Yup.string().required('Name is required'), email: Yup.string().email('Invalid email address').required('Email is required'), password: Yup.string() .min(6, 'Password must be at least 6 characters') .required('Password is required') });
Step 3: Implement the Form Fields and Display Errors
Using Formik, you can use the Field component for inputs and ErrorMessage for displaying validation errors.
<Formik initialValues={{name: '',email: '',password: ''}} validationSchema={validationSchema} onSubmit={(values) => { console.log(values); }}> <Form> <label htmlFor="name">Name</label> <Field name="name" type="text" /> <ErrorMessage name="name" component="div" /> <label htmlFor="email">Email</label> <Field name="email" type="email" /> <ErrorMessage name="email" component="div" /> <label htmlFor="password">Password</label> <Field name="password" type="password" /> <ErrorMessage name="password" component="div" /> <button type="submit">Submit</button> </Form> </Formik>
Complete Code
Here’s the complete code with more validation for the sign-up form:
import React from "react"; import { Formik, Form, Field, ErrorMessage } from "formik"; import * as Yup from "yup"; const SignupForm = () => { const validationSchema = Yup.object({ name: Yup.string() .min(3, "Name must be at least 3 characters") .max(50, "Name can be at most 50 characters") .required("Name is required") .matches(/^[A-Za-z\s]+$/, "Name should only contain letters and spaces"), email: Yup.string() .email("Invalid email address") .required("Email is required") .matches( /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,"Email must be a valid format"), password: Yup.string() .min(8, "Password must be at least 8 characters") .max(20, "Password can be at most 20 characters") .required("Password is required") .matches( /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,20}$/, "Password must contain at least one letter, one number, and be 8-20 characters long" ), }); return ( <Formik initialValues={{name: "",email: "",password: "",}} validationSchema={validationSchema} onSubmit={(values) => { console.log(values); }}> <Form> <label htmlFor="name">Name</label> <Field name="name" type="text" /> <ErrorMessage name="name" component="div" /> <label htmlFor="email">Email</label> <Field name="email" type="email" /> <ErrorMessage name="email" component="div" /> <label htmlFor="password">Password</label> <Field name="password" type="password" /> <ErrorMessage name="password" component="div" /> <button type="submit">Submit</button> </Form> </Formik> ); }; export default SignupForm;
## For More deeper Information, check out the official [Formik documentation].
Conclusion
Formik offers a straightforward way to handle forms in React, simplifying state management and validation. By combining it with Yup, you can create robust forms with minimal effort. Try it out in your next React project to experience the difference!