How to use Formik in React Js?

Introduction

Formik is a popular form management library for React applications. It simplifies the process of building and handling forms by abstracting away much of the boilerplate code associated with form handling, validation, and submission.

Using Formik in a React application involves several steps, from setting up the form component to handling form submission and validation. Below is a simple guide on how to use Formik to create and manage forms in React.

Step 1. Setting Up Your React Project

Start by setting up a new React project using the Create React App or any other method you prefer.

npx create-react-app registration-form
cd registration-form
npm start

Step 2. Installing Formik and CSS Dependencies

Install Formik and any CSS libraries you want to use for styling. In this example, we'll use Bootstrap for CSS.

npm install formik bootstrap

Step 3. Creating the Registration Form Component

Create a new file named RegistrationForm.js inside the src directory. This file will contain our registration form component.

// RegistrationForm.js
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import 'bootstrap/dist/css/bootstrap.min.css';
import './RegistrationForm.css';

const RegistrationForm = () => {
  return (
    <div className="registration-form">
      <h1>Registration Form</h1>
      <Formik
        initialValues={{ firstName: '', lastName: '', email: '', password: '' }}
        validationSchema={Yup.object({
          firstName: Yup.string().required('First Name is required'),
          lastName: Yup.string().required('Last 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'),
        })}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        <Form>
          <div className="form-group">
            <label htmlFor="firstName">First Name</label>
            <Field type="text" name="firstName" className="form-control" />
            <ErrorMessage name="firstName" component="div" className="error-message" />
          </div>

          <div className="form-group">
            <label htmlFor="lastName">Last Name</label>
            <Field type="text" name="lastName" className="form-control" />
            <ErrorMessage name="lastName" component="div" className="error-message" />
          </div>

          <div className="form-group">
            <label htmlFor="email">Email Address</label>
            <Field type="email" name="email" className="form-control" />
            <ErrorMessage name="email" component="div" className="error-message" />
          </div>

          <div className="form-group">
            <label htmlFor="password">Password</label>
            <Field type="password" name="password" className="form-control" />
            <ErrorMessage name="password" component="div" className="error-message" />
          </div>

          <button type="submit" className="btn btn-primary">Submit</button>
        </Form>
      </Formik>
    </div>
  );
};

export default RegistrationForm;

Step 4. Creating CSS Styling

Create a new file named RegistrationForm.css in the src directory to add custom styling for your form.

/* RegistrationForm.css */
.registration-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.error-message {
  color: red;
  font-size: 0.8em;
}

.form-group {
  margin-bottom: 20px;
}

Step 5. Using the Registration Form Component

Import and use the RegistrationForm component in your App.js file.

// App.js
import React from 'react';
import RegistrationForm from './RegistrationForm';

function App() {
  return (
    <div className="App">
      <RegistrationForm />
    </div>
  );
}

export default App;

Step 6. Testing

Run your React application and test the registration form by filling it out. Validation errors should be displayed for any empty fields or incorrectly formatted email addresses.

Run your React

Summary

We've successfully built a registration form in React using Formik and styled it using CSS. You can further customize the form's appearance and behavior as needed.