Skip to content
the poor coder

form with formik and yup react js

Poor Man
Published
Reading time
3 min read
On this page

Form with Formik and Yup in React JS#

Formik is a popular library in React JS that helps in managing form state and validation. Yup is a library that provides a simple way to validate objects. Together, Formik and Yup make form validation much easier in React JS.

Installation#

You can install Formik and Yup by running the following commands in the terminal:

Bash
$ npm install formik yup

Usage#

First, import the necessary libraries:

JavaScript
// Import libraries
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

Then, define the validation schema using Yup:

JavaScript
// Define validation schema
const validationSchema = Yup.object().shape({
  name: Yup.string()
    .min(2, 'Name must be at least 2 characters.')
    .max(50, 'Name must be at most 50 characters.')
    .required('Name 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.'),
});

Then, define the form using Formik:

JavaScript
// Define form
const form = (
  <Formik
    initialValues={{
      name: '',
      email: '',
      password: '',
    }}
    onSubmit={values => {
      console.log(values);
    }}
    validationSchema={validationSchema}
  >
    {({ errors, touched }) => (
      <Form>
        <div>
          <label htmlFor="name">Name</label>
          <Field name="name" />
          <ErrorMessage name="name" />
        </div>

        <div>
          <label htmlFor="email">Email</label>
          <Field name="email" />
          <ErrorMessage name="email" />
        </div>

        <div>
          <label htmlFor="password">Password</label>
          <Field name="password" type="password" />
          <ErrorMessage name="password" />
        </div>

        <button type="submit">Submit</button>
      </Form>
    )}
  </Formik>
);

The form contains three fields: name, email, and password. Each field has a label, a Field component, and an ErrorMessage component. The onSubmit function is called when the form is submitted, and the values of the fields are logged to the console. The validationSchema is used to validate the values of the fields.

Alternative Approach#

Another way to use Formik and Yup is to define the form as a separate component:

JavaScript
// Define form component
const MyForm = () => (
  <Formik
    initialValues={{
      name: '',
      email: '',
      password: '',
    }}
    onSubmit={values => {
      console.log(values);
    }}
    validationSchema={validationSchema}
  >
    {({ errors, touched }) => (
      <Form>
        <div>
          <label htmlFor="name">Name</label>
          <Field name="name" />
          <ErrorMessage name="name" />
        </div>

        <div>
          <label htmlFor="email">Email</label>
          <Field name="email" />
          <ErrorMessage name="email" />
        </div>

        <div>
          <label htmlFor="password">Password</label>
          <Field name="password" type="password" />
          <ErrorMessage name="password" />
        </div>

        <button type="submit">Submit</button>
      </Form>
    )}
  </Formik>
);

// Use form component
const App = () => (
  <div>
    <MyForm />
  </div>
);

In this approach, the form is defined as a separate component, which can be used in any other component.

Conclusion#

Formik and Yup make form validation easy in React JS. By defining the validation schema using Yup and using Formik to manage the form state and validation, you can create forms quickly and easily.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC