@conform-to/react
Version:
Conform view adapter for react
231 lines • 9.28 kB
TypeScript
import { type FieldName, type FormValue, type Serialize, type SubmissionResult, createGlobalFormsObserver } from '@conform-to/dom/future';
import { useEffect } from 'react';
import type { FormContext, IntentDispatcher, FormMetadata, Fieldset, GlobalFormOptions, FormOptions, FieldMetadata, Control, Selector, UseFormDataOptions, ValidateHandler, ErrorHandler, SubmitHandler, FormState, FormRef, BaseErrorShape, DefaultErrorShape, BaseSchemaType, InferInput, InferOutput } from './types';
import { StandardSchemaV1 } from './standard-schema';
export declare const INITIAL_KEY = "INITIAL_KEY";
export declare const GlobalFormOptionsContext: import("react").Context<GlobalFormOptions & {
observer: ReturnType<typeof createGlobalFormsObserver>;
}>;
export declare const FormContextContext: import("react").Context<FormContext<string>[]>;
/**
* Provides form context to child components.
* Stacks contexts to support nested forms, with latest context taking priority.
*/
export declare function FormProvider(props: {
context: FormContext;
children: React.ReactNode;
}): React.ReactElement;
export declare function FormOptionsProvider(props: Partial<GlobalFormOptions> & {
children: React.ReactNode;
}): React.ReactElement;
export declare function useFormContext(formId?: string): FormContext;
/**
* Core form hook that manages form state, validation, and submission.
* Handles both sync and async validation, intent dispatching, and DOM updates.
*/
export declare function useConform<FormShape extends Record<string, any>, ErrorShape, Value = undefined, SchemaValue = undefined>(formRef: FormRef, options: {
key?: string | undefined;
defaultValue?: Record<string, FormValue> | null | undefined;
serialize: Serialize;
intentName: string;
lastResult?: SubmissionResult<NoInfer<ErrorShape>> | null | undefined;
onValidate?: ValidateHandler<ErrorShape, Value, SchemaValue> | undefined;
onError?: ErrorHandler<ErrorShape> | undefined;
onSubmit?: SubmitHandler<FormShape, NoInfer<ErrorShape>, NoInfer<Value>> | undefined;
}): [FormState<ErrorShape>, (event: React.FormEvent<HTMLFormElement>) => void];
/**
* The main React hook for form management. Handles form state, validation, and submission
* while providing access to form metadata, field objects, and form actions.
*
* It can be called in two ways:
* - **Schema first**: Pass a schema as the first argument for automatic validation with type inference
* - **Manual configuration**: Pass options with custom `onValidate` handler for manual validation
*
* @see https://conform.guide/api/react/future/useForm
* @example Schema first setup with zod:
*
* ```tsx
* const { form, fields } = useForm(zodSchema, {
* lastResult,
* shouldValidate: 'onBlur',
* });
*
* return (
* <form {...form.props}>
* <input name={fields.email.name} defaultValue={fields.email.defaultValue} />
* <div>{fields.email.errors}</div>
* </form>
* );
* ```
*
* @example Manual configuration setup with custom validation:
*
* ```tsx
* const { form, fields } = useForm({
* onValidate({ payload, error }) {
* if (!payload.email) {
* error.fieldErrors.email = ['Required'];
* }
* return error;
* }
* });
*
* return (
* <form {...form.props}>
* <input name={fields.email.name} defaultValue={fields.email.defaultValue} />
* <div>{fields.email.errors}</div>
* </form>
* );
* ```
*/
export declare function useForm<Schema extends BaseSchemaType, ErrorShape extends BaseErrorShape = DefaultErrorShape, Value = InferOutput<Schema>>(schema: Schema, options: FormOptions<InferInput<Schema>, ErrorShape, Value, Schema, string extends ErrorShape ? never : 'onValidate'>): {
form: FormMetadata<ErrorShape>;
fields: Fieldset<InferInput<Schema>, ErrorShape>;
intent: IntentDispatcher<InferInput<Schema>>;
};
/**
* @deprecated Use `useForm(schema, options)` instead for better type inference.
*/
export declare function useForm<FormShape extends Record<string, any> = Record<string, any>, ErrorShape extends BaseErrorShape = DefaultErrorShape, Value = undefined>(options: FormOptions<FormShape, ErrorShape, Value, undefined, undefined extends Value ? 'onValidate' : never> & {
/**
* @deprecated Use `useForm(schema, options)` instead for better type inference.
*
* Optional standard schema for validation (e.g., Zod, Valibot, Yup).
* Removes the need for manual onValidate setup.
*
*/
schema: StandardSchemaV1<FormShape, Value>;
}): {
form: FormMetadata<ErrorShape>;
fields: Fieldset<FormShape, ErrorShape>;
intent: IntentDispatcher<FormShape>;
};
export declare function useForm<FormShape extends Record<string, any> = Record<string, any>, ErrorShape extends BaseErrorShape = DefaultErrorShape, Value = undefined>(options: FormOptions<FormShape, ErrorShape, Value, undefined, 'onValidate'>): {
form: FormMetadata<ErrorShape>;
fields: Fieldset<FormShape, ErrorShape>;
intent: IntentDispatcher<FormShape>;
};
/**
* A React hook that provides access to form-level metadata and state.
* Requires `FormProvider` context when used in child components.
*
* @see https://conform.guide/api/react/future/useFormMetadata
* @example
* ```tsx
* function ErrorSummary() {
* const form = useFormMetadata();
*
* if (form.valid) return null;
*
* return (
* <div>Please fix {Object.keys(form.fieldErrors).length} errors</div>
* );
* }
* ```
*/
export declare function useFormMetadata(options?: {
formId?: string;
}): FormMetadata;
/**
* A React hook that provides access to a specific field's metadata and state.
* Requires `FormProvider` context when used in child components.
*
* @see https://conform.guide/api/react/future/useField
* @example
* ```tsx
* function FormField({ name, label }) {
* const field = useField(name);
*
* return (
* <div>
* <label htmlFor={field.id}>{label}</label>
* <input id={field.id} name={field.name} defaultValue={field.defaultValue} />
* {field.errors && <div>{field.errors.join(', ')}</div>}
* </div>
* );
* }
* ```
*/
export declare function useField<FieldShape = any>(name: FieldName<FieldShape>, options?: {
formId?: string;
}): FieldMetadata<FieldShape>;
/**
* A React hook that provides an intent dispatcher for programmatic form actions.
* Intent dispatchers allow you to trigger form operations like validation, field updates,
* and array manipulations without manual form submission.
*
* @see https://conform.guide/api/react/future/useIntent
* @example
* ```tsx
* function ResetButton() {
* const buttonRef = useRef<HTMLButtonElement>(null);
* const intent = useIntent(buttonRef);
*
* return (
* <button type="button" ref={buttonRef} onClick={() => intent.reset()}>
* Reset Form
* </button>
* );
* }
* ```
*/
export declare function useIntent<FormShape extends Record<string, any>>(formRef: FormRef): IntentDispatcher<FormShape>;
/**
* A React hook that lets you sync the state of an input and dispatch native form events from it.
* This is useful when emulating native input behavior — typically by rendering a hidden base input
* and syncing it with a custom input.
*
* @example
* ```ts
* const control = useControl(options);
* ```
*/
export declare function useControl(options?: {
/**
* The initial value of the base input. It will be used to set the value
* when the input is first registered.
*/
defaultValue?: string | string[] | File | File[] | null | undefined;
/**
* Whether the base input should be checked by default. It will be applied
* when the input is first registered.
*/
defaultChecked?: boolean | undefined;
/**
* The value of a checkbox or radio input when checked. This sets the
* value attribute of the base input.
*/
value?: string;
/**
* A callback function that is triggered when the base input is focused.
* Use this to delegate focus to a custom input.
*/
onFocus?: () => void;
}): Control;
/**
* A React hook that lets you subscribe to the current `FormData` of a form and derive a custom value from it.
* The selector runs whenever the form's structure or data changes, and the hook re-renders only when the result is deeply different.
*
* @see https://conform.guide/api/react/future/useFormData
* @example
* ```ts
* const value = useFormData(formRef, formData => formData?.get('fieldName') ?? '');
* ```
*/
export declare function useFormData<Value = any>(formRef: FormRef, select: Selector<FormData, Value>, options: UseFormDataOptions & {
acceptFiles: true;
}): Value;
export declare function useFormData<Value = any>(formRef: FormRef, select: Selector<URLSearchParams, Value>, options?: UseFormDataOptions & {
acceptFiles?: boolean;
}): Value;
/**
* useLayoutEffect is client-only.
* This basically makes it a no-op on server
*/
export declare const useSafeLayoutEffect: typeof useEffect;
/**
* Keep a mutable ref in sync with the latest value.
* Useful to avoid stale closures in event handlers or async callbacks.
*/
export declare function useLatest<Value>(value: Value): import("react").MutableRefObject<Value>;
//# sourceMappingURL=hooks.d.ts.map