parkmodelsandcabins.com

Effortless Form Management in React Using Formik and Yup

Written on

Chapter 1: Introduction to Formik and Yup

Formik is a powerful library that streamlines form handling in React applications. When paired with Yup, it provides a robust solution for form validation. This article will explore how to effectively manage form inputs using Formik.

Form handling in React with Formik and Yup

Section 1.1: Setting Up Form Validation with withFormik

To introduce validation in our form component, we can enhance it using the withFormik higher-order component. Here's an example:

import React from "react";

import { withFormik } from "formik";

const MyForm = (props) => {

const {

values,

touched,

errors,

handleChange,

handleBlur,

handleSubmit

} = props;

return (

<form onSubmit={handleSubmit}>

<input

type="text"

onChange={handleChange}

onBlur={handleBlur}

value={values.email}

name="email"

/>

{errors.email && touched.email && <div id="feedback">{errors.email}</div>}

<button type="submit">Submit</button>

</form>

);

};

const MyEnhancedForm = withFormik({

mapPropsToValues: () => ({ email: "" }),

validate: (values) => {

const errors = {};

if (!values.email) {

errors.email = "Required";

} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(values.email)) {

errors.email = "Invalid email address";

}

return errors;

},

handleSubmit: (values, { setSubmitting }) => {

setTimeout(() => {

alert(JSON.stringify(values, null, 2));

setSubmitting(false);

}, 1000);

},

displayName: "BasicForm"

})(MyForm);

export default function App() {

return (

<div className="App">

<MyEnhancedForm />

</div>

);

}

In the example above, we create the MyForm component to capture the necessary properties. The values object holds the input values, while touched indicates which fields have been interacted with. The errors object contains any validation errors defined in the validate method.

Section 1.2: Enhanced Validation with Yup

To simplify form validation, we can leverage the Yup library alongside Formik. Below is an example of how to implement this:

import React from "react";

import { Formik, Form, Field } from "formik";

import * as Yup from "yup";

const SignupSchema = Yup.object().shape({

email: Yup.string().email("Invalid email").required("Required")

});

export const ExampleForm = () => (

<div>

<h1>Signup</h1>

<Formik

initialValues={{ email: "" }}

validationSchema={SignupSchema}

onSubmit={(values) => {

console.log(values);

}}

>

{({ errors, touched }) => (

<Form>

<Field name="email" type="email" />

{errors.email && touched.email ? <div>{errors.email}</div> : null}

<button type="submit">Submit</button>

</Form>

)}

</Formik>

</div>

);

export default function App() {

return (

<div className="App">

<ExampleForm />

</div>

);

}

In this example, we create a validation schema using Yup.object().shape(), where we define the validation criteria for the email field. The email method checks for a valid email format, and the required method ensures that the field cannot be left empty.

Chapter 2: Conclusion

By integrating Formik with Yup, we can significantly enhance our form validation process, making it both efficient and straightforward.

The first video, "React Formik Tutorial with Yup (React Form Validation)", demonstrates the integration of Formik with Yup for effective form validation.

The second video, "React Multi Step Form With Formik + Yup - React Tutorial", showcases how to create multi-step forms using Formik and Yup.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Self-Taught Coders: The Unsung Heroes of Development

Exploring how self-taught programmers often outperform their formally trained counterparts.

Unlock the Secrets to Building Strong and Muscular Legs

Discover the essential exercises to strengthen your legs and enhance your fitness journey.

Unlock Your Athletic Potential with Mindfulness Training

Explore how mindfulness techniques can elevate your athletic performance and mental fitness.

Title: Embracing a Wholesome Diet: My Insights and Tips

Discover my journey with healthy eating, tips for a balanced diet, and the importance of whole foods.

OpenAI’s Latest Embedding Model: Transforming the Landscape

OpenAI's new embedding model, text-embedding-ada-002, offers superior performance and cost-effectiveness, revolutionizing text processing and coding tasks.

The Rise of AI Companionship: A $10,000 Monthly Investment

Exploring the trend of AI companions and the financial commitment involved, alongside market predictions and emotional learning capabilities.

# Unlock Your Courage: Embrace Risks with These 3 Essential Keys

Discover three essential keys to unlock your courage and embrace risks for a more fulfilling life.

AI Wealth Creation Blueprint: Transforming Finance for Everyone

Discover how the AI Wealth Creation Blueprint is democratizing finance, making advanced investment strategies accessible to all.