Building Forms with Formik in React: Complete Code Examples and Explanations

Follow on LinkedIn

In this article, we are building a simple form to understand how to build a form with Formik in React application, Here we are building a simple form with name and email fields and we are validating these forms fields and submitting it.

First, we need to install React and Formik in our application by running the below command in the terminal.

npm install react react-dom formik

Let’s start building our Forms with Formik in React application.

Now create a file userForm.js to create our form component.

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

// Define the validation schema using Yup
const validationSchema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
});

const UserForm = () => {
  // Initial form values
  const initialValues = {
    name: '',
    email: '',
  };

  // For handling form submit
  const handleSubmit = (values, { resetForm }) => {
    console.log(values);
    resetForm();
  };

  return (
    <div>
      <h2>User Information</h2>
      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
      >
        <Form>
          <div>
            <label htmlFor="name">Name</label>
            <Field type="text" id="name" name="name" />
            <ErrorMessage name="name" component="div" className="error" />
          </div>
          <div>
            <label htmlFor="email">Email</label>
            <Field type="email" id="email" name="email" />
            <ErrorMessage name="email" component="div" className="error" />
          </div>
          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </div>
  );
};

export default UserForm;

In the above file first we need to import the necessary components and functions from Formik and Yup.
Yop is basically used for defining the schema for validating our form fields, it specify the validation rules for our forms fields.

Now, we also need some initial values for our form and we are defining it with a variable initialValues and assigning all fields to blank string.

There is a function called handleSubmit which is basically handling the form submission and consoling the result and after that resetting the form values by calling a function called resetForm(), which is an in built function and we can take it as a property inside a handleSubmit function.

We are importing two more field components Field and ErrorMessage, Field is to define the input elements and ErrorMessage to display the schema validation error messages.

Now, its time to add our userForm component inside our app.js file.

import React from 'react';
import UserForm from './UserForm';

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

export default App;

That’s it! You can run you app now by npm start command and check the form. React and Formik is very good combination for making a project that has a lot of forms usecase.

If you have any doubt, please comment. Happy Coding 🙂

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

×