Skip to main content

<FormProvider>

The <FormProvider> component is used to set up the form context.

Props

<Form> takes the following props:

PropertyTypeDefaultDescription
childrenReactNodeThe <FormProvider> children
errorsIErrorForm errors (see errors guide for more information)
formRefObject<HTMLFormElement>Form ref
formPropsIFormPropsForm props to add on your form component
messagesRecord<string, string>Given custom messages
mode'all' | 'blur' | 'change' | 'submit'Chosen Validation strategy
onChangeIOnChangeHandlerChange handler (see type casting guide and controlled components guide for more information)
onErrorIOnErrorHandlerManual error handler (see controlled components guide for more information)
onResetIOnResetHandlerReset handler (see reset guide for more information)
onSubmitIOnSubmitHandlerSubmit handler (see submit guide for more information)
registerIRegisterInternal usage
resetIFormResetManual reset function
revalidateMode'blur' | 'change' | 'submit'Chosen re-validation strategy
statesIFormStatesForm states
subscribeISubscribeFunction to subscribe to state change information)
unregisterIUnregisterInternal usage
useNativeValidationbooleanChoice for native validation or not
validateIFormValidateManual validate function
watchIWatchManual 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>
);
}