Formik Basics 🎯

beginner
25 min

Formik Basics 🎯

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!

What is Formik? 📝

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.

Why Use Formik? 💡

Formik offers numerous benefits such as:

  • Automatic form state management
  • Easy form validation
  • Error handling
  • Controlled and uncontrolled form support
  • Form reset and submit

Getting Started 🎯

Installing Formik

First, make sure you have react and react-dom installed in your project. If not, run:

bash
npm install --save react react-dom

Now, to install Formik and its CSS, run:

bash
npm install formik yup

Importing Formik

In your React component file, import Formik and other necessary dependencies:

javascript
import React from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup';

Creating a Form with Formik 🎯

Now let's build a simple form to get a feel of how Formik works.

javascript
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:

  1. Created a validation schema using Yup.
  2. Set initial values for the form.
  3. Defined the form submission handler.
  4. Wrapped the form with the Formik component and provided the schema, initial values, and submission handler.
  5. Used Field and ErrorMessage components to handle form fields and errors.

Formik Form State 📝

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.

javascript
const { values } = useFormikContext(); console.log(values.email); // Output: current email value

Formik Form Validation 💡

Formik 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.

javascript
<Field name="email" type="email" /> <p>{values.email.isValid ? 'Email is valid' : 'Email is not valid'}</p>

Formik Form Submission 💡

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.

javascript
onSubmit={(values, { setSubmitting }) => { // Submit form data here console.log(JSON.stringify(values)); setSubmitting(false); }}

Formik Form Reset 💡

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.

javascript
onSubmit={(values, { setSubmitting, resetForm }) => { // Submit form data here console.log(JSON.stringify(values)); setSubmitting(false); resetForm(); }}

Quiz 🎯

Quick Quiz
Question 1 of 1

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! 💻🚀