Skip to main content

useFormContext

useFormContext is for retrieving the form context when the <Form> or the <FormProvider> components are set.

Parameters

There is no parameters for useFormContext.

Returns

useFormContext returns an object with the following shape (it is basically the same as the return from useForm without formProps):

PropertyTypeDescription
errorsIErrorForm errors (see errors guide for more information)
formRefObject<HTMLFormElement>Form ref
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 (warning: these are not react states)
subscribeISubscribeFunction to subscribe to state change (see the form state guide for more 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

0
import type { FormEvent } from 'react';
import type { IFormValues } from '@per-form/react';
import type { IProps } from '../types';
import { FormProvider, useForm, useFormContext } from '@per-form/react';

function Inputs() {
const { errors } = useFormContext();
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>
);
}