I am trying to make a form with Next.js, typescript and formik + yup libraries.
I have 2 situations. When there is a input and formik gets value and second when input is not visible and button should work as onClick button.
I have to use formik.
When there is no input field handleSubmit does not fires at all.
import { useFormik } from "formik";
import { object, SchemaOf, string } from "yup";
import { Button } from "@components/Button";
import { Input } from "@components/Input";
import styles from "./Form.module.scss";
import React from "react";
interface FormValues {
name: string;
}
const initialValues: FormValues = {
name: "",
};
export const Form = () => {
const username = false;
const validationSchema: SchemaOf<FormValues> = object({
name: string().min(1).max(30, "maxLengthError").required("requiredError"),
});
const handleAlternative = (values) => console.log("Alternative", values);
const formik = useFormik({
initialValues,
validationSchema,
onSubmit: (values, { resetForm }) => {
console.log(values);
handleAlternative(values);
resetForm();
},
});
return (
<form onSubmit={formik.handleSubmit} className={styles.form}>
{username && (
<Input
id="name"
type="name"
label={"Name"}
value={formik.values.name}
error={!!formik.errors.name}
errorMessage={formik.errors.name}
onChange={formik.handleChange}
/>
)}
<div className="justify-center gap-4">
<Button
type="submit"
disabled={!!username && (!formik.isValid || !formik.dirty)}
>
Submit
</Button>
</div>
</form>
);
};
I have tried to change type=’onSubmit’ to onClick= but then formik does not work at all.
I am using Next.js, formik, yup
>Solution :
All you need to do is remove
.required("requiredError") when there is no input.
If you need .required when input is on you can add it like this:
const nameSchema: SchemaOf<FormValues> = object({
name: string().min(1).max(30, "maxLengthError").required("requiredError"),
});
const validationSchema: SchemaOf<FormValues> = username ? nameSchema : object();