In this article, you will fastly start using Formik and Yup(Conditional) with custom hooks in your React project.
Summary
Formik is using for building forms in React. Formik is providing lots of feature (less code, easy maintable, custom hooks, easy integrate and more)that making life easier while creating forms. You can easily build schema for validation with Yup.
Installing Formik
npm i formik
Installing Yup
npm i yup
Introduction of Formik
- Getting values in and out of form state
- Validation and error messages
- Handling form submission
// Simple form with formik
import React from "react";
import { useFormik } from "formik";
const SignupForm = () => {
const formik = useFormik({
initialValues: {
email: "",
},
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
},
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="email">Email Address</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
<button type="submit">Submit</button>
</form>
);
};
Problem statement
The problem is that formik form has two inputs. One is select and other is text input select has two option 'yes' or 'no'. If user select the 'Yes' then user must write about the dish on the other hand if user select the 'no' there is no validation.
Solution
I had a formik form where I needed to enter the passphrase if it was required and make it optional if it wasn't required. While validating the field using 'Yup' I needed a way to conditionally change the validation logic for the field. For this, I need to use the when() function from Yup which allows us to change the validation logic applied to a field based on some conditions. After this I pass the values with and make condition that if user select the Yes (User want to eat chicken)from the option then user must write about chicken dishes which one user want otherwise no condition. Write about the dish depend on the user selection.
Formik useFormik custom hook
const formik = useFormik({
initialValues: {
dropdown: "",
ChickenDish: "",
},
Yup Schema
validationSchema: Yup.object({
dropdown: Yup.string(),
ChickenDish: Yup.string().when("dropdown", {
is: (dropdown) => dropdown === "Yes",
then: Yup.string().required("* Required"),
}),
Top comments (0)