Integration utilities for react-hook-form.
npm install @paragrav/rhf-utilsIntegration and utility library for react-hook-form (and zod). Declaratively configure your forms via global and form-level options.
- TypeScript-first
- global configuration (🔗 RhfUtilsClientConfig section)
- RHF (UseFormProps) and utilities (RhfUtilsFormOptions) options defaults
- inject your own hooks and UI (FormComponent)
- server error transformation (onSubmitErrorUnknown) ✨
- handle cancel prompt (useCanFormBeCancelled) ✨
- RHF FormState.errors logging/throwing (RhfUtilsClientConfig.fieldErrors) ✨
- form-level configuration (🔗 RhfUtilsZodForm section)
- RHF and utilities options overrides
- extendable utilities options type (RhfUtilsFormOptions)
- throw error (FormSubmitError) in submit handler to add errors to RHF context and fail submit
- handle submit error (onSubmitError / useLastSubmitError)
- context injection for children (RhfUtilsZodForm.Children), including:
- formId, formRef, RHF context, utilities options
- schema-typed Controller component and FormSubmitError class
- form state relay (🔗 FormStateRelayContextProvider section) ✨
- access specific form's state from outside that form/provider
- assign forms into groups and watch collectively
- simpler/flatter FieldErrors structure (🔗 FlatFieldErrors section)
- find orphans errors (🔗 orphan errors section) ✨
- context groups errors into all, fields, roots, and orphans (useFlatFieldErrorsContext)
- safer FieldValues type (🔗 SafeFieldValues section)
- zod support, including input/output types for transformations
- ~2.8kB min+gzip core (excluding peer dependencies)
``sh`
npm install @paragrav/rhf-utils # npm
pnpm add @paragrav/rhf-utils # pnpm
yarn add @paragrav/rhf-utils # yarn
- 🔗 Config (RhfUtilsClientConfig): define your global config (optional)RhfUtilsClientConfigProvider
- 🔗 Provider (): add to your global stackRhfUtilsZodFormWithProviders
- 🔗 Form With Providers (): use as form componentFormStateRelayContextProvider
- 🔗 Form State Relay (): relay form state
Create a config (RhfUtilsClientConfig) object with desired global config and default options. Config applies across all forms, and defaults can be overridden per form.
`tsxUseFormProps
export const rhfUtilsClientConfig: RhfUtilsClientConfig = {
defaults: {
// globally-relevant subset of RHF's options
rhf: {
mode: 'onSubmit',
},
// RhfUtilsFormOptions (see further below)
utils: {
stopSubmitPropagation: true,
devTool: import.meta.env.DEV && { placement: 'top-right' },
},
// global default native form props
form: {
noValidate: true,
className: 'my-form-class',
},
},
// optional form component to use (defaults to primitive HTML form)
FormComponent: Form.Root,
// inject your own hooks and components
// into all RhfUtilsZodForm instances
FormChildren: (
// RhfUtilsFormComponentProps
{
formId, // unique id string
formRef, // form element ref
context, // rhf UseFormReturn (without proxy formState)
options, // RhfUtilsFormOptions (with any custom props)
Controller, // rhf controller (SafeFieldValues-typed; no schema at this level)
FormSubmitError, // error class (SafeFieldValues-typed; no schema at this level)
children, // RhfUtilsZodForm's Children instance
},
) => {
useMyGlobalFormHook();
// form-level control of your own hooks/behaviors via custom option props
// (see "Extend RhfUtilsFormOptions" section for more info)
useMyOptionalFormHook({
enabled: !!options.enableMyOptionalFormHook,
});
return (
<>
{/ RhfUtilsZodForm.Children "outlet" (see "Component Hierarchy" section) /}
{children}
{/ root errors list /}
>
);
},
// hook that returns callback to determine whether form can be cancelled
// if true, RhfUtilsZodForm.onCancel at form-level is called (e.g., parent component hides form)FormComponent
// this allows you to handle non-navigational blocking/prompting
// NOTE: this library is router-agnostic, so navigation blocking should happen elsewhere
// (i.e., calling your own hook in )
useCanFormBeCancelled: () => {
const { isDirty } = useFormState();
// return callback to be called at event-time
return ({ options }) =>
!options.enableMyPrompter || // my prompter option not enabled
!isDirty || // or rhf form state not dirty
confirm('Are you sure you want to cancel?'); // or user confirms
},
// non-FormSubmitError thrown in onSubmit
// use case: handle and transform server error data for frontend
onSubmitErrorUnknown: (
error, // unknown
) => {
// return FormSubmitFieldErrors object to be merged to RHF context errors
if (isMyServerError(error))
return transformMyServerErrorToFormSubmitFieldErrors(error);
},
// RHF FormState.errors output for debugging
fieldErrors: {
// callbacks to determine when to output information about field errors
// provided FlatFieldErrorsContext (all, fields, roots, orphans, hasOrphans)
// (See "Orphan Errors" section below for more info.)
output: {
// determine when to console ("debug" or "error")
console: ({ hasOrphans }) =>
// facilitate local debugging of form validation
(import.meta.env.DEV && { type: 'debug' }) ||
// console error for reporting on prod
(hasOrphans && { type: 'error' }),
// callback to determine when to throw an error based on field errors
throw: ({ hasOrphans }) =>
// bring attention to orphans locally
import.meta.env.DEV && hasOrphans,
},
},
};
`
Add the context provider to your global provider stack.
`tsx`
{children}
Currently, only zod schemas are supported.
`tsxChildren
email: z.string().min(1).email(),
password: z.string().min(1),
passwordConfirm: z.string().min(1),
})}
defaultValues={{ email: '', password: '', passwordConfirm: '' }}
getApiData={({ email, password }) => ({ email, password })}
// cancel handler (passed to below)RhfUtilsClientConfig.useCanFormBeCancelled
// execution routed through , if providedformState
onCancel={handleCancel}
// submit handlers
onBeforeSubmitInvariants={async (
{ input, output, api }, // schema input (form values), output; api data (via getApiData)
context, // UseRhfUtilsFormOnSubmitContext (id, ref, rhf context (without proxy formState), utils options, schema-typed FormSubmitError class)
event, // SubmitEvent
) => [
[
'passwordConfirm', // type safe
'Passwords must match.',
data.password === data.passwordConfirm,
],
]}
onBeforeSubmit={({ input, output, api }, context, event) => {
if (!isValid(input.email))
throw new context.FormSubmitError({
email: { message: 'Email is invalid.' },
});
}}
// submit handler
onSubmit={({ input, output, api }, context, event) => registerService(api)}
onSubmitSuccess={(onSubmitResult, { input, output, api }, context, event) =>
navigate('/app/' + onSubmitResult.id)
}
// handle error declaratively (i.e., no throw/catch)
onSubmitError={({ error, context, event }) => {
handleError(error);
}}
onSubmitFinally={() => {
setState();
}}
// form-specific options/overrides (merged with defaults)
rhf={{
mode: 'onBlur',
}}
utils={{
submitOnWatch: { debounce: 250 },
// custom option props
// (see "Extend RhfUtilsFormOptions" section)
enableMyOptionalFormHook: true,
}}
// surfaced form element attributes
id="my-form-id"
className="my-special-form-class" // merged with global defaults
// other form element attributes
form={{ noValidate: true }} // merged with global defaults
// fields
Children={({
// UseRhfUtilsFormChildrenProps
formId, // unique id string (auto-gen if not supplied)
formRef, // ref
context, // rhf UseFormReturn (without proxy )
options, // RhfUtilsFormOptions
Controller, // schema-typed rhf controller
FormSubmitError, // schema-typed error class
onCancel, // wrapped cancel handler from above
}) => (
<>
render={({ field, formState: { isSubmitting } }) => (
)}
/>
>
)}
/>
`
Children prop takes a component which is rendered as a child of the form (and, if supplied, of RhfUtilsClientConfig.FormComponent). It receives UseRhfUtilsFormChildrenProps as props, including a type-safe Controller component.
If you prefer to define your Children component as standalone, you will need to specify any dependencies as props (e.g., onEvent callback):
`tsx
const Children: RhfUtilsUseZodFormChildrenFC<
typeof schema,
{ onEvent: () => void } // other props (if required)
> = ({ ... }) => {};
// or
function Children({ ... }: RhfUtilsUseZodFormChildrenProps<
typeof schema,
{ onEvent: () => void } // other props (if required)
>) {}
`
And pass other props manually, if applicable:
`tsx`
props={{ onEvent: handleEvent }}
/>
)}
/>
For each form instance, RhfUtilsZodForm renders as the following:
`tsx`
Sometimes you need to control the nesting of the Form element. For example, to appease HTML rules or expand the scope of the Provider.
`tsx
`
For similar pattern, especially across more than one form, see Form State Relay section.
This is an Error-based class that you can use to throw a schema-typed error in your submit handler.
(Internally, it uses FormSubmitFieldErrors type's structure, which is a flat, simplified version of RHF's FieldErrors. It differs from FlatFieldError only in that it is narrower. It allows field names from your schema and root.${string} keys. And only type (optional) and message props for error.)
`tsx`
if (!isValid(data))
throw new FormSubmitError({
'street.address': { message: 'Street address invalid.' },
});
}}
/>
Any non-FormSubmitError error thrown from your submit handler (e.g., fetch/axios error) can be transformed by RhfUtilsClientConfig's onSubmitErrorUnknown callback. This takes an unknown error and can return a FormSubmitFieldErrors object, which is merged into RHF's form state errors.
Most common use case will be transforming backend errors to frontend shape expected by RHF.
Sometimes, perhaps outside any specific FormContext, you need direct access to the actual error object that was thrown, which caused the last submit to fail. The useLastSubmitError hook allows you to do just this. (You can probably handle most form-specific cases via onSubmitErrorUnknown, which receives error as well.)
These built-in options can be set globally and/or per form.
`ts
type RhfUtilsFormOptions = {
/* Stop propagation of submit event. /
stopSubmitPropagation?: boolean;
/* Request submit on change. /
submitOnChange?: { debounce?: number };
/**
* Reset form values and state (e.g., isDirty, etc.) after submit -- on success and/or error.
* - defaults: reset current values to defaults (e.g., clear form)current
* - : reset defaults to current values (keep current values)
*/
resetOnSubmitted?: {
success?: { values: 'defaults' | 'current' };
error?: { values: 'defaults' };
};
/* Control dev tool options. (Lazy-loaded when truthy value supplied.) /
devTool?: boolean | Pick
};
`
If you need access to options deeper in your component structure, use useRhfUtilsContext to receive RhfUtilsContext object, which includes formId, formRef, and options settings.
Use useRhfUtilsContextRequestSubmit hook to get requestSubmit function for current form ref in context. This is useful when you need to trigger form submission programatically.
Extend RhfUtilsFormOptions with custom options, which get passed to RhfUtilsClientConfig's ChildrenWrapper and RhfUtilsZodForm's Children components via options prop. These can take any shape, and allow you to override your own functionality at form-level.
`tsx
import '@paragrav/rhf-utils';
declare module '@paragrav/rhf-utils' {
export interface Register {
RhfUtilsFormOptions: {
/* Custom props for your custom options/hooks/behaviors. /
enableMyPrompter?: boolean;
enableMyOptionalFormHook?: boolean;
configMyOptionalFormHook?: MyCustomFormHookConfig;
};
}
}
`
Sometimes you need to access one or more forms' state outside the form (and its providers).
Use case: display a form's errors (or any other state) outside form and its context.
`tsx
;
`
Push can be configured via FormStateRelayPusher component or useFormStateRelayPush hook with FormStateRelayPushOptions options.
`ts`
type FormStateRelayPushOptions = {
group?: string | string[]; // assign group(s) to watch multiple forms in aggregate
flaggedState?: {
isMounted?: true; // flag form when mounted -- e.g., forms that are hidden by default
};
};
`tsx
function WatchOutsideFormContext() {
// FormStateWithUtils (either via RHF -- when requested within form context -- or relay when not)
const formState = useFormStateWithUtilsViaRhfOrRelay();
}
// when watching a single form, original RHF FormState with generally-typed SafeFieldValues
type FormStateRelayed = FormState
`
The useFormStateWithUtilsViaRhfOrRelay hook uses useFormStateRelayPullOnlyOrThrow internally. It provides additional naivety when consumer doesn't know which context between RHF or Relay is present. (This is useful when building base components -- e.g., buttons -- which may exist outside of form context.)
Use cases:
- disable parent form when ANY child is "flagged" (i.e., dirty)
- disable ALL children when parent is "flagged" (i.e., submitting)
- confirm navigation when ANY mounted form is "flagged" (i.e., dirty)
`tsx
function ParentForm() {
const childrenFormState = useFormStateRelayWatchGroup('children'); // FormStateRelayedAggregated
return (
);
}
function ChildForm() {
const parentFormState = useFormStateRelayWatchId('parent'); // FormStateRelayed
return (
);
}
type FormStateRelayedAggregated = FormStateRelayed & {
// object values reduced to booleans for non-empty-ness
dirtyFields: boolean;
touchedFields: boolean;
validatingFields: boolean;
error: boolean;
// composites
isSubmitUnsuccessful: boolean;
isMountedFlagged: boolean; // via RelayedFormOptions['flaggedState']['isMounted']
};
`
You can also aggregate any (i.e., all) forms via useFormStateRelayPullAny, which returns FormStateRelayedAggregated as well.
`tsx`
FlatFieldErrors type is a flattened, simplified version of RHF's FieldErrors. Keys represent flattened, dot-notation field paths.
Use useFlatFieldErrorsContext() hook, which returns an object with errors grouped by all, fields, roots, orphans records, and boolean values for hasErrors and hasOrphans.
For the purposes of debugging and/or logging, you can configure when form state errors are outputted (i.e., console and/or thrown) via RhfUtilsClientConfig.fieldErrors.output (example at the top).
The concept of an "orphan" error is any errant schema property that could prohibit users from submitting a valid form because its input is missing or non-existent.
Programatically, an "orphan" is any form state error that meets ALL of the following criteria:
- non-field -- i.e., no RHF-supplied ref on FieldError objectroot
- non-root -- i.e., not or root.${string} pathRhfUtilsNonFieldErrorMarker
- no corresponding "marker" in DOM (i.e., )
This is because:
- field errors (with refs) are assumed to be displayed next to their respective inputref
- root errors (non-field, without s) are assumed to always be listed for display
- all other errors must be marked as displayed to distinguish from being an orphan
_See RhfUtilsNonFieldErrorMarker section below for more information about when and why marker is needed._
#### Using orphan errors
Detected orphans can be accessed via any of the following:
- RhfUtilsClientConfig.fieldErrors.output -- e.g., config per environment:throw
- _development_: to facilitate discovery and debuggingconsole.error
- _production_: to facilitate reportinguseFlatFieldErrorsContext()
- hookall
- returns an object with list of errors grouped by , fields (with ref), roots, orphans records, and includes computed booleans hasErrors and hasOrphansuseFlatFieldErrorsContextHasOnlyOrphans
- boolean value from
_If you don't need orphan detection, you can skip this section. By default, orphan detection still occurs but doesn't otherwise do anything._
To get accurate orphan detection, you must use RhfUtilsNonFieldErrorMarker when displaying any non-root non-field errors. (Example further below.)
There is little harm in including it consistently for all individual errors displayed. (DOM traversal to find marker only occurs if error is non-field AND non-root, which is not typical.)
#### When is the marker required? _(example of non-root non-field error)_
A typical example is a field array with a required minimum number of items -- e.g., items: z.array(...).min(1).
When there are zero items, the error is non-field and non-root. You would probably display this error (manually) near the field array, using something like RHF's ErrorMessage component.
In order to NOT detect this as an orphan, it must be explicitly "marked" as displayed using RhfUtilsNonFieldErrorMarker.
You should incorporate RhfUtilsNonFieldErrorMarker into your own component library's error message display component.
`tsx`
_If you include the marker in bulk error lists, it will defeat the purpose of the marker. Only use marker for individual errors. Therefore, if you are ONLY listing a summary of all errors, without individual displays, you will need to use the marker manually._
#### trpcClientErrorToFormSubmitFieldErrorsSchemaTransformer
zod-based schema for transforming TRPCClientErrorLike server errors to FormSubmitFieldErrors.
#### makeOnSubmitTrpcClientErrorHandler
HOF to make a onSubmitErrorUnknown handler for TRPC.io server errors (with fallback callback for non-TRPC errors).
`ts`
onSubmitErrorUnknown: makeOnSubmitTrpcClientErrorHandler((error) => {
// non-trpc error
}),
This library uses SafeFieldValues type which uses unknown instead of any`.
- react
- react-dom
- react-hook-form
- @hookform/resolvers
- @hookform/devtools (optional)
- zod
- flat _(805B min+gzip)_