Refactor form to use useFormik and FormikProvider

Replaced Formik component with useFormik hook and FormikProvider. This change simplifies the form implementation and separates the form's logic and presentation. The form now benefits from more direct access to formik methods and state.
This commit is contained in:
2024-08-08 21:37:09 +02:00
parent 4dda70effc
commit cde2a01dd9
+29 -20
View File
@@ -1,7 +1,7 @@
import React, {useState} from "react";
import './GenericForm.css';
import {useNavigate} from 'react-router-dom'
import {ErrorMessage, Field, Form, Formik, FormikValues} from "formik";
import {ErrorMessage, Field, Form, FormikProvider, FormikValues, useFormik} from "formik";
import {Step, UserInput, FormData} from './formInterfaces';
import * as Yup from "yup";
@@ -56,30 +56,33 @@ const GenericForm = (formData: FormData) => {
setCurrentStep(current => Math.max(current - 1, 0))
}
const formik = useFormik({
initialValues: userInput,
validationSchema: spec,
onSubmit: (values) => {
handleSubmit(values);
},
});
const {
touched,
errors,
isValid,
handleChange,
values,
setFieldTouched,
} = formik;
const [prevLength, setPrevLength] = useState(0);
return (
<div>
<div>
<h1>{formData.title}</h1>
</div>
<div className="container">
<Formik
initialValues={userInput}
validationSchema={spec}
onSubmit={(values: FormikValues) => {
handleSubmit(values);
}}
>
{({
touched,
errors,
isValid,
handleChange,
values,
setFieldTouched
}) => (
<div>
<FormikProvider value={formik}>
<Form>
<div>
<div>
<label>
<label>
@@ -131,9 +134,14 @@ const GenericForm = (formData: FormData) => {
/>
)
}
</label>
</div>
<div>
<label>
<ErrorMessage name={steps[currentStep].name} component="div"/>
</label>
</div>
<div>
<button style={{marginLeft: 0}} className="button-outer" type="button" onClick={prev} disabled={currentStep === 0}>
Previous
</button>
@@ -146,9 +154,10 @@ const GenericForm = (formData: FormData) => {
hidden={currentStep !== (steps.length - 1)}
disabled={!isValid || currentStep !== (steps.length - 1)}
/>
</div>
</div>
</Form>
)}
</Formik>
</FormikProvider>
</div>
</div>
);