First timer...
I am using formik with yup form validation in react typescript and trying to get formik.touched && formik.errors for nested object .
whatever I tried not working
how should I get to the nested object ?
{formik.touched.address?.state && formik.errors.address?.state && ( <p className="text-danger">{formik.errors.address?.state}</p> )}
validationSchema: yup.object({
firstName: yup.string().required().min(2),
lastName: yup.string().required().min(2),
email: yup.string().required().email(),
address: yup.object({
country: yup.string().required().min(2),
state: yup.string().min(2), }),
}),
return
<div className="form-floating col-6 mb-3 mt-3">
<input
type="text"
className="form-control"
id="floatingState"
placeholder="John Doe"
name="state"
onChange={formik.handleChange}
value={formik.values.address?.state}
onBlur={formik.handleBlur}
></input>
<label`your text` htmlFor="floatingState">State</label>
{formik.touched.address?.state && formik.errors.address?.state && (
<p className="text-danger">{formik.errors.address?.state}</p>
)}
</div>
First you need to set
initialValuesfor address if you haven'tAnd change value of
nameattribute of input toname="address.state", sincestateis inside address object.