I'm using react-hook-form with Yup library for managing my forms in my app.
I'm trying to create dynamic Yup schema According to my component state.
For example:
import React, { useContext } from "react";
import { useForm } from "react-hook-form";
import { useHistory } from "react-router-dom";
import { FirstFormContext } from "../context/FirstFormContext";
import { SecondFormContext } from "../context/SecondFormContext";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
const schema = yup.object().shape({
email: yup.string().email().min(2), // <-- Here I want to access the value
address: yup.string().min(2).max(20)
});
const SecondForm = () => {
const { secondFormData, setSecondFormData } = useContext(SecondFormContext);
const { firstFormData } = useContext(FirstFormContext);
const { register, handleSubmit } = useForm({
resolver: yupResolver(schema),
context: firstFormData.type // <---- Passing the variable
});
const history = useHistory();
const onSubmit = (data) => {
setSecondFormData(data);
history.push("/end-page");
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<button
style={{ display: "block", marginBottom: "20px" }}
onClick={() => history.push("/")}
>
Go back
</button>
{firstFormData.type === "one" ? (
<input
defaultValue={secondFormData.email}
placeholder="email"
{...register("email", { required: true })}
/>
) : firstFormData.type === "two" ? (
<input
defaultValue={secondFormData.address}
placeholder="address"
{...register("address", { required: true })}
/>
) : null}
<button type="submit" style={{ display: "block", marginTop: "20px" }}>
Next
</button>
</form>
);
};
export default SecondForm;
As you can see, inside my component I'm passing the context to useForm hook and I want to access it in the Yup schema above the SecondForm component.
How can I achieve it ?
Thank you.
I solved it that way:
Inside useForm hook
const { register, handleSubmit } = useForm({
resolver: yupResolver(schema),
context: { type: firstFormData.type }
});
In my schema :
const schema = yup.object().shape({
email: yup
.string()
.email()
.min(2)
.when("$type", (type, schema) => {
console.log(type);
if (type === "one") {
return schema.required();
}
return;
}),
address: yup.string().min(2).max(20)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With