<FormProvider>
The <FormProvider>
component is used to set up the form context.
Props
<Form>
takes the following props:
Property | Type | Default | Description |
---|---|---|---|
children | ReactNode | The <FormProvider> children | |
errors | IError | Form errors (see errors guide for more information) | |
form | RefObject<HTMLFormElement> | Form ref | |
formProps | IFormProps | Form props to add on your form component | |
messages | Record<string, string> | Given custom messages | |
mode | 'all' | 'blur' | 'change' | 'submit' | Chosen Validation strategy | |
onChange | IOnChangeHandler | Change handler (see type casting guide and controlled components guide for more information) | |
onError | IOnErrorHandler | Manual error handler (see controlled components guide for more information) | |
onReset | IOnResetHandler | Reset handler (see reset guide for more information) | |
onSubmit | IOnSubmitHandler | Submit handler (see submit guide for more information) | |
register | IRegister | Internal usage | |
reset | IFormReset | Manual reset function | |
revalidateMode | 'blur' | 'change' | 'submit' | Chosen re-validation strategy | |
states | IFormStates | Form states | |
subscribe | ISubscribe | Function to subscribe to state change information) | |
unregister | IUnregister | Internal usage | |
useNativeValidation | boolean | Choice for native validation or not | |
validate | IFormValidate | Manual validate function | |
watch | IWatch | Manual watch function (see watch guide for more information) |
See here for the types.
Usage
To set up the <FormProvider>
destructure the context value from the useForm
hook like this:
0
import type { FormEvent } from 'react';
import type { IFormValues } from '@per-form/react';
import type { IProps } from '../types';
import { FormProvider, useForm, useFormErrors } from '@per-form/react';
function Inputs() {
const errors = useFormErrors();
return (
<>
<input name="text" required />
{errors.all.text && <div className="error">{errors.all.text}</div>}
</>
);
}
export default function Demo({ useNativeValidation }: IProps) {
function handleSubmit(_e: FormEvent<HTMLFormElement>, values: IFormValues) {
console.log(values);
}
const { formProps, ...context } = useForm({
onSubmit: handleSubmit,
useNativeValidation,
});
return (
<FormProvider {...context}>
<form {...formProps}>
<Inputs />
<button type="submit">Submit</button>
</form>
</FormProvider>
);
}