Moved logic from Form to controller

This commit is contained in:
Ceferino Patino 2022-08-10 17:54:37 -05:00
commit a480a76f96
2 changed files with 25 additions and 45 deletions

View file

@ -1,38 +1,19 @@
import React, { useEffect } from 'react';
import React from 'react';
import { Button, TextField, Typography } from '@mui/material';
import { useForm } from '../contexts/FormContext';
export default function Form({ formik, fields }) {
const { setContent } = useForm();
useEffect(() => {
setContent('');
}, []);
function handleChange(event) {
if (event.target.id === 'text')
setContent(event.target.value);
}
export default function Form({ formik, fields, handleChange }) {
return (
<form onSubmit={formik.handleSubmit} onChange={handleChange}>
{fields.map((field) => (
<span key={field.id}>
<Typography>{field.title}</Typography>
<TextField {...field} fullWidth/>
<TextField {...field} fullWidth />
</span>
))}
<Button
fullWidth
type='submit'
variant='contained'
color='primary'
sx={{ mt: '1vh' }}
>
<Button fullWidth type='submit' variant='contained' color='primary' sx={{ mt: '1vh' }}>
Submit
</Button>
</form>
);
}

View file

@ -1,5 +1,8 @@
import { useEffect } from 'react';
import { useFormik } from 'formik';
import { Form } from 'components';
import { useForm } from 'contexts';
export default function FormController({
fields,
@ -8,33 +11,29 @@ export default function FormController({
validationSchema,
children,
}) {
const { setContent } = useForm();
useEffect(() => {
setContent('');
}, [setContent]);
const handleChange = (e) => setContent(e.target.value);
const formik = useFormik({
initialValues: fields.reduce(
(acc, { id }) => ({ ...acc, [id]: '' }),
{}
),
initialValues: fields.reduce((acc, { id }) => ({ ...acc, [id]: '' }), {}),
onSubmit,
validate,
validateOnChange: false,
validationSchema,
});
const formikFields = fields.map(({ id, helperText = () => 0, ...field }) => ({
id,
...field,
error: Boolean(formik.touched[id] && formik.errors[id]),
helperText: helperText(formik.values[id]) || (formik.touched[id] && formik.errors[id]),
onChange: formik.handleChange,
value: formik.values[id],
}));
const formikFields = fields.map(
({ id, helperText = () => 0, ...field }) => ({
id,
...field,
error: Boolean(formik.touched[id] && formik.errors[id]),
helperText:
helperText(formik.values[id]) ||
(formik.touched[id] && formik.errors[id]),
onChange: formik.handleChange,
value: formik.values[id],
})
);
return Form({
formik,
fields: formikFields,
children,
});
return <Form {...{ formik, fields: formikFields, children, handleChange }} />;
}