Welcome to this comprehensive guide on Formik, a popular React library for handling forms in a more efficient and user-friendly way! By the end of this tutorial, you'll have a solid understanding of how to utilize Formik in your projects. Let's dive in!
Formik is a library that simplifies form handling in React applications. It provides a higher-order component and a form context to manage form state, validation, and submission easily.
Formik offers numerous benefits such as:
First, make sure you have react and react-dom installed in your project. If not, run:
npm install --save react react-domNow, to install Formik and its CSS, run:
npm install formik yupIn your React component file, import Formik and other necessary dependencies:
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';Now let's build a simple form to get a feel of how Formik works.
const SignupForm = () => {
const signupSchema = Yup.object().shape({
email: Yup.string().email('Invalid email address').required('Email is required'),
password: Yup.string().min(8, 'Password must be 8 characters or more').required('Password is required'),
});
return (
<Formik
initialValues={{ email: '', password: '' }}
validationSchema={signupSchema}
onSubmit={(values, { setSubmitting }) => {
// Submit form data here
console.log(JSON.stringify(values));
setSubmitting(false);
}}
>
<Form>
<label htmlFor="email">Email</label>
<Field name="email" type="email" />
<ErrorMessage name="email" />
<label htmlFor="password">Password</label>
<Field name="password" type="password" />
<ErrorMessage name="password" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
};In this example, we've created a simple signup form using Formik. Here's what we've done:
Formik component and provided the schema, initial values, and submission handler.Field and ErrorMessage components to handle form fields and errors.Formik automatically manages form state, making it easy to access and update form values. To access form values, you can use the values prop provided by Formik.
const { values } = useFormikContext();
console.log(values.email); // Output: current email valueFormik handles form validation automatically, making it easy to validate form fields against the provided schema. To check if a field is valid, use the isValid prop provided by the Field component.
<Field name="email" type="email" />
<p>{values.email.isValid ? 'Email is valid' : 'Email is not valid'}</p>When the form is submitted, the form submission handler defined in the Formik component will be called with the form values and additional props such as setSubmitting.
onSubmit={(values, { setSubmitting }) => {
// Submit form data here
console.log(JSON.stringify(values));
setSubmitting(false);
}}Formik provides a resetForm method to reset the form to its initial state. You can use this method in the form submission handler to reset the form after it's been submitted.
onSubmit={(values, { setSubmitting, resetForm }) => {
// Submit form data here
console.log(JSON.stringify(values));
setSubmitting(false);
resetForm();
}}What does Formik provide for React form handling?
That's it for this beginner-friendly guide on Formik basics! With this knowledge, you can now create efficient and user-friendly forms in your React projects. Happy coding! 💻🚀