Git Product home page Git Product logo

learning-react-formik's Introduction

React Formik

What?

Formik is a small library that helps you deal with forms in React. Formik keeps track of form's state and handles form submission.

Why?

  1. Managing form data or form state
  2. Form submission
  3. Form validation and displaying error messages

How to use formik?

Import the useFormik hook

import { useFormik } from "formik";

Create a formik instance

const formik = useFormik({
        initialValues: {
            name: "",
            email: "",
            password: "",
        },
    });

The initialValues 'name', 'email', 'password' correspond to the name attribute of the input fields.

Add the onChange and value props to the input fields

<form>
    <input
        type="password"
        name="password"
        value={formik.values.password}
        onChange={formik.handleChange}
    />
    <button type="submit">Submit</button>
</form>
  • formik.values.password is the value of the input field. And password is the name attribute of the input field.

  • handleChange is a function (formik helper) that updates the form state.

  • formik.values is an object that contains the form state and will give us access to the form data.

Add the onSubmit event to the form

<form onSubmit={formik.handleSubmit}>
</form>
  • formik.handleSubmit is a function that handles form submission.

Add the onSubmit function to the formik instance

const formik = useFormik({
        initialValues: {
            name: "",
            email: "",
            password: "",
        },
        onSubmit: (values) => {
            console.log(values);
        },
    });
  • values is an object that contains the form data that we were referring to using formik.values.

Validate the form

Formik lets you define a validation function that will run when the form is submitted. This validation function needs to be assigned to the validate property of the formik instance in the useFormik hook.

const formik = useFormik({
    initialValues: {
      name: "",
      email: "",
      password: "",
    },
    onSubmit: (values) => {
      console.log("Values: ", values);
    },
    validate: (values) => {
      // errors.name, errors.email, errors.password
      //name, email, password are the name attributes of the input fields
      const errors: any = {};
      if (!values.name) {
        errors.name = "Required";
      }
      if (!values.email) {
        errors.email = "Required";
      } 
      if (!values.password) {
        errors.password = "Required";
      }
      return errors;
    },
  });

Display the error messages

{
    formik.errors.name ? (
        <div className="text-red-500 text-sm mt-1">{formik.errors.name}</div>
    ) : null
}

To make sure the error is shown only for visited fields, add the onBlur prop to the input fields with the value formik.handleBlur.

<input
    type="text"
    name="name"
    id="name"
    onChange={formik.handleChange}
    value={formik.values.name}
    onBlur={formik.handleBlur}
    placeholder="Emelia Erickson"
    className=""
/>

We can keep track of the visited fields using the touched property of the formik instance.

{
    formik.touched.name && formik.errors.name ? (
        <div className="text-red-500 text-sm mt-1">{formik.errors.name}</div>
    ) : null
}

Yup

To make the form validation more robust, we can use the Yup library. Yup is a JavaScript schema builder for value parsing and validation.

Install Yup

npm install yup

Import Yup

import * as Yup from "yup";

Create a validation schema

const validationSchema = Yup.object({
    name: Yup.string().required("Name is required"),
    email: Yup.string().email("Invalid email address").required("Email is required"),
    password: Yup.string().required("Password is required"),
});

The object method of Yup is used to create a schema object. The schema object is used to define the validation rules for the form fields.

Pass the validation schema to the useFormik hook

const formik = useFormik({
    initialValues: {
        name: "",
        email: "",
        password: "",
    },
    onSubmit: (values) => {
        console.log("Values: ", values);
    },
    validationSchema: validationSchema,
});

learning-react-formik's People

Contributors

anushkakohli avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.