React context provider for form state management and validation with yup.
The code to be implemented is in the folder utils/form.
// App.tsx
import { FormProvider } from '@/utils/form';
import { MyForm } from '@/components';
export default App = () => (
<FormProvider
defaultValues={firstName: 'John', lastName: 'Doe'}
>
<MyForm/>
</FormProvider>
);
// MyForm.tsx
import { useFormContext } from '@/utils/form';
import { MyInputField } from '@/components';
export default MyForm = () => {
const { register } = useFormContext();
return (
<form>
<MyInputField {...register('firstName')} />
<MyInputField {...register('lastname')} />
</form>
);
};
Provides context for state management and validation.
Its generic type T
default value is Record<any, any>
and is used to type the data of the form if needed.
defaultValues: T
: default form valuesvalidationMethod?: FormValidationMethod
: form validation method, betweenchange
,blur
andundefined
(to submit form via the context's method only)yupSchema?: any
: yup schema for validationchangeDebounceTime?: number
: debounce time used to update context (and trigger change submit) in millisecondsonSubmit?: (values: T) => void
: form submit eventonValidSubmit?: (values: T) => void
: form submit event that fires only ifyupSchema
is valid
Provides the FormProvider
's children access to the form context.
Its generic type T
default value is Record<any, any>
and is used to type the data of the form if needed.
values: T
: form values as they are in the current context (NB: they can differ from the ones submitted)touchedValues: (keyof T)[]
: field keys that have been touchederrors: Record<keyof T, string>
: yup errorsregister: (name: keyof T, options?: Partial<FormField<T>>) => FormField<T>
: this method is used to register a field in the context, it sets the following props of the input/component (and all of them can be overrided by the method's options or directly via the input/component props) :name: keyof T
fieldValue: string
validationMethod?: FormValidationMethod
status?: FormFieldStatus
statusMessage?: string
onChange?: FormFieldUpdate<T>
updateValues: (values: Partial<T>) => void
: update some values of the formsubmit: () => void
: submit the formreset: () => void
: reset the form to its default values
In the project directory, you can run npm start
to start the sandbox (at http://localhost:3000).