Introduction🚀
Creating forms in React can be a bit of a hassle. There are a lot of moving parts, from handling input validation to managing form state. That's where Formik comes in. In this blog post, we'll explore why Formik is handy for building forms in React, what exactly Formik is, and how to implement it in your projects.
Why do we need Formik for forms?
Picture this: You're building a web application with React, and you need to create a form for user input. Without Formik, you'd have to manually manage the state of each input field, handle validation, and deal with form submission. It can get messy and time-consuming, especially as your forms become more complex.
Formik came into the picture to solve these pain points. It provides a simpler and more intuitive way to build forms in React. With Formik, you can easily manage form state, handle validation, and streamline the form submission process, saving you time and headaches.
What is Formik?
Formik is a form management library for React. It simplifies the process of building forms by abstracting away the complexities of managing form state and handling user input. With Formik, you can easily create robust and maintainable forms without writing boilerplate code.
One of the key features of Formik is its ability to handle form validation. You can define validation rules for your form fields and display error messages to users when they enter invalid data. Formik also provides a straightforward way to handle form submission, including asynchronous submissions and form reset.
With Formik, developers can define validation schemas using Yup, a powerful schema validation library. Yup allows developers to define validation rules for each form field and provides meaningful error messages to users when validation fails.
Build a Signup Page with Formik
Now that we understand why Formik is useful, let's see how we can implement it in our React projects.
Installation: First, install Formik and its dependencies using npm or yarn.
npm install formik yup
or
yarn add formik yup
Basic Usage: Import Formik and other necessary components into your React component.
import { Formik, Form, Field, ErrorMessage } from 'formik';
Create a Form: Wrap your form fields inside the Formik component and define initial form values and validation rules. Now, let's dive into building a simple signup page with Formik. We'll include fields for name, username, phone number, address, email, and password, along with validation rules.
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
// Define validation schema using Yup
const SignupSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
username: Yup.string().min(8, 'Username must be at least 8 characters').required('Username is required'),
phone: Yup.string().matches(/^[0-9]{10}$/, 'Invalid phone number').required('Phone number is required'),
address: Yup.string().required('Address is required'),
email: Yup.string().email('Invalid email').required('Email is required'),
password: Yup.string().min(8, 'Password must be at least 8 characters').required('Password is required'),
});
const SignupForm = () => (
<div>
<h1>Sign Up</h1>
<Formik
initialValues={{
name: '',
username: '',
phone: '',
address: '',
email: '',
password: '',
}}
validationSchema={SignupSchema}
onSubmit={(values) => {
// Handle form submission
console.log(values);
}}
>
<Form>
<div>
<label htmlFor="name">Name</label>
<Field type="text" name="name" />
<ErrorMessage name="name" component="div" />
</div>
<div>
<label htmlFor="username">Username</label>
<Field type="text" name="username" />
<ErrorMessage name="username" component="div" />
</div>
<div>
<label htmlFor="phone">Phone Number</label>
<Field type="text" name="phone" />
<ErrorMessage name="phone" component="div" />
</div>
<div>
<label htmlFor="address">Address</label>
<Field type="text" name="address" />
<ErrorMessage name="address" component="div" />
</div>
<div>
<label htmlFor="email">Email</label>
<Field type="email" name="email" />
<ErrorMessage name="email" component="div" />
</div>
<div>
<label htmlFor="password">Password</label>
<Field type="password" name="password" />
<ErrorMessage name="password" component="div" />
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);
export default SignupForm;
Now, open the terminal and run the development server by running the command -
npm run start
Your form will look something like this -
Now play around with the form and try to see the validations for the form.
Conclusion: Formik is a powerful tool for building forms in React. It simplifies the process of managing form state, handling user input, and validating form data. By abstracting away the complexities of form management, Formik allows you to focus on building great user experiences. Whether you're working on a simple contact form or a complex multi-step wizard, Formik can help you get the job done efficiently and effectively.
Now that you've learned how to build a signup page using Formik, feel free to explore further and incorporate additional features to enhance your forms even more. So why not give Formik a try in your next React project? Your future self will thank you for it! Happy coding!
To read more about tech & open source, you can follow me on Hashnode and Twitter (@MadhuSaini22) and If this blog helped you in any way then you can sponsor my work and show love and support.
Thank you so much for reading! 👩💻