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
):
Property | Type | Description |
---|---|---|
errors | IError | Form errors (see errors guide for more information) |
form | RefObject<HTMLFormElement> | Form ref |
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 (warning: these are not react states) |
subscribe | ISubscribe | Function to subscribe to state change (see the form state guide for more 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
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>
);
}