DEV Community

Cover image for Create React form auto validated using formik and yup
Jose Latines
Jose Latines

Posted on

Create React form auto validated using formik and yup

Formik and Yup are two powerful libraries in the React ecosystem that streamline form handling and validation. Let's dive into what makes them special and why they can greatly enhance your development experience! πŸš€

πŸ“ Understanding Formik

Formik is a flexible and intuitive library that helps you manage form state, validation, and submission in React applications. It simplifies the process of handling complex forms by providing an elegant API and seamless integration with React components. πŸ“Š

πŸ“‹ Introducing Yup

Yup is a JavaScript schema validation library that works seamlessly with Formik. It allows you to define validation rules and constraints for your form inputs, ensuring that user input meets your specified requirements. With Yup, form validation becomes more efficient and reliable. βœ…

πŸ€” Why Should You Use Formik and Yup?

By utilizing Formik and Yup, you can significantly reduce the boilerplate code traditionally associated with form management in React. These libraries provide a declarative approach to form handling, making your code more readable, maintainable, and efficient. ⚑️

πŸ’‘ The Best Approach: A Closer Look

While there are various methods to create Formik forms, let me share my personal favorite for its simplicity and readability. By following this approach, you'll be able to build forms more efficiently and save time during development. 🎯


import { useFormik } from "formik";
import * as Yup from "yup";

const validationSchema = Yup.object({
    email: Yup.string().label("Email is required").email().required(),
});

const initialValues = {
    email: "",
};

function FormikForm() {
    const handleSubmit = async credentials => {
        try {
            alert("Credentials received");
            console.log(credentials);
        } catch (error) {
            console.error(error);
        }
    };

    const formik = useFormik({
        validationSchema,
        initialValues,
        onSubmit: handleSubmit,
    });
    return (
        <form
            onSubmit={formik.handleSubmit}
            className="py-8 text-base leading-6 space-y-4 text-gray-700 sm:text-lg sm:leading-7"
        >
            <div>
                <div className="mb-4">
                    <label
                        className="block text-gray-700 text-sm font-bold mb-2"
                        htmlFor={"email"}
                    >
                        Email
                    </label>
                    <input
                        className={`${
                            formik.touched["email"] && formik.errors["email"]
                                ? "border-red-400"
                                : "border-gray-300"
                        }`}
                        type="text"
                        name={"email"}
                        id={"email"}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        value={formik.values["email"]}
                    />

                    {formik.touched["email"] && formik.errors["email"] && (
                        <span className="text-red-400">{formik.errors["email"]}</span>
                    )}
                </div>
            </div>

            <div className="relative">
                <button
                    type="submit"
                    disabled={formik.isSubmitting}
                    className={`btn ${formik.isSubmitting && "disabled"}`}
                >
                    Login
                </button>
            </div>
        </form>
    );
}

export default FormikForm;

Enter fullscreen mode Exit fullscreen mode

If you found this content helpful and informative, please let me know in the comments section. Don't forget to follow me on Instagram @gregglatines for more exciting content! πŸ˜ŠπŸ‘

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay