Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

form-atoms/form-atoms


Atomic form primitives forJotai

npm i form-atoms jotai

Supported by FlexStack


BundlephobiaTypesCode coverageBuild statusNPM VersionMIT License

Features

  • Renders what changes and nothing else
  • Strongly typed allowing you to quickly iterate on durable code
  • Tiny (<3kB gzipped) but powerful API
  • Nested/array fields without parsing field names
  • Dynamic fields - you aren't stuck with your initial config
  • Controlled inputs because no, uncontrolled inputs are not preferrable
  • Ready for concurrent React - validation updates have a lower priority
  • Familiar API that is very similar to other form libraries
  • Async field-level validation withZod andValibot support

Quick start

Check out the example on CodeSandbox ↗

import{fieldAtom,useInputField,formAtom,useForm}from"form-atoms";constnameFormAtom=formAtom({name:{first:fieldAtom({value:""}),last:fieldAtom({value:""}),},});functionForm(){const{ fieldAtoms, submit}=useForm(nameFormAtom);return(<formonSubmit={submit((values)=>{console.log(values);})}><Fieldlabel="First name"atom={fieldAtoms.name.first}/><Fieldlabel="Last name"atom={fieldAtoms.name.last}/></form>);}functionField({ label, atom}){constfield=useInputField(atom);return(<label><span>{label}</span><input{...field.props}/></label>);}

Concepts

Jotai was born to solve extra re-renderissue in React. Extra re-render is a render process that produces the sameUI result, with which users won't see any differences.

Like Jotai, this library was built to solve the extra re-render issue withReactForms. It takes a bottom-up approach using Jotai's atomic model.In practice that means thatformAtom() derives its state fromfieldAtom(). For example, validation occurs at the field-levelrather than the form-level. Normally that would pose a problem for fields withvalidation that is dependent on other state or other fields, but usingfieldAtom'svalidate function allows you to read the value of other atoms.

Theform-atoms minimal API is written to be ergonomic and powerful. Itfeelslike other form libraries (even better in my opinion). You don't lose anythingby using it, but you gain a ton of performance and without footguns.

Table of contents

Field atomsDescription
fieldAtom()An atom that represents a field in a form. It manages state for the field, including the name, value, errors, dirty, validation, and touched state.
useField()A hook that returnsstate andactions of a field atom fromuseFieldState, anduseFieldActions.
useInputField()A hook that returnsprops,state, andactions of a field atom fromuseInputFieldProps,useFieldState, anduseFieldActions.
useInputFieldProps()A hook that returns a set of props that can be destructured directly into an<input>,<select>, or<textarea> element.
useTextareaField()A hook that returnsprops,state, andactions of a field atom fromuseTextareaFieldProps,useFieldState, anduseFieldActions.
useTextareaFieldProps()A hook that returns a set of props that can be destructured directly into a<textarea> element.
useSelectField()A hook that returnsprops,state, andactions of a field atom fromuseSelectFieldProps,useFieldState, anduseFieldActions.
useSelectFieldProps()A hook that returns a set of props that can be destructured directly into a<select> element.
useFieldState()A hook that returns the state of a field atom. This includes the field's value, whether it has been touched, whether it is dirty, the validation status, and any errors.
useFieldActions()A hook that returns a set of actions that can be used to interact with the field atom state.
useFieldInitialValue()A hook that sets the initial value of a field atom. Initial values can only be set once per scope. Therefore, if the initial value used is changed during rerenders, it won't update the atom value.
useFieldValue()A hook that returns the value of a field atom.
useFieldErrors()A hook that returns the errors of a field atom.
Form atomsDescription
formAtom()An atom that derives its state fields atoms and allows you to submit, validate, and reset your form.
useForm()A hook that returns an object that contains thefieldAtoms and actions to validate, submit, and reset the form.
useFormState()A hook that returns the primary state of the form atom including values, errors, submit and validation status, as well as thefieldAtoms. Note that this hook will cuase its parent component to re-render any time those states change, so it can be useful to use more targeted state hooks likeuseFormStatus.
useFormActions()A hook that returns a set of actions that can be used to update the state of the form atom. This includes updating fields, submitting, resetting, and validating the form.
useFormValues()A hook that returns the values of the form atom.
useFormErrors()A hook that returns the errors of the form atom.
useFormStatus()A hook that returns thesubmitStatus andvalidateStatus of the form atom.
useFormSubmit()A hook that returns a callback for handling form submission.
ComponentsDescription
<Form>A React component that renders form atoms and their fields in an isolated scope using a Jotai Provider.
<InputField>A React component that renders field atoms with initial values. This is useful for fields that are rendered as native HTML elements because the props can unpack directly into the underlying component.
<TextareaField>A React component that renders field atoms with initial values. This is useful for fields that are rendered as native HTML elements because the props can unpack directly into the underlying component.
<SelectField>A React component that renders field atoms with initial values. This is useful for fields that are rendered as native HTML elements because the props can unpack directly into the underlying component.
<Field>A React component that renders field atoms with initial values. This is useful for fields that aren't rendered as native HTML elements.
Utility TypesDescription
FormValuesA utility type for inferring the value types of a form's nested field atoms.
FormErrorsA utility type for inferring the error types of a form's nested field atoms.
ValidatorDescription
form-atoms/valibotA validator that can be used with theValibot library to validate fields.
form-atoms/zodA validator that can be used with theZod library to validate fields.

Recipes

  1. How to validate on(blur, change, touch, submit)
  2. How to validate a field conditional to the state of another field
  3. How to validate a field asynchronously
  4. How to validate using a Zod schema
  5. How to create a nested fields
  6. How to create an array of fields
  7. How to read field metadata (dirty, touched, error) in the onSubmit callback

Projects usingform-atoms


Field atoms

fieldAtom()

An atom that represents a field in a form. It manages state for the field,including the name, value, errors, dirty, validation, and touched state.

Arguments

NameTypeRequired?Description
configFieldAtomConfig<Value>YesThe initial state and configuration of the field.

FieldAtomConfig

typeFieldAtomConfig<Value>={/**   * Optionally provide a name for the field that will be added   * to any attached `<input>`, `<select>`, or `<textarea>` elements   */name?:string;/**   * The initial value of the field   */value:Value;/**   * The initial touched state of the field   */touched?:boolean;/**   * Transform the value of the field each time `setValue` is   * called, before validation and when the field is initialized.   * Optionally subscribe to other atoms via the `get` function.   */preprocess?:(value:Value,get:Getter)=>Value;/**   * A function that validates the value of the field any time   * one of its atoms changes. It must either return an array of   * string error messages or undefined. If it returns undefined,   * the validation is "skipped" and the current errors in state   * are retained.   */validate?:(state:{/**     * A Jotai getter that can read other atoms     */get:Getter;/**     * The current value of the field     */value:Value;/**     * The dirty state of the field     */dirty:boolean;/**     * The touched state of the field     */touched:boolean;/**     * The event that caused the validation. Either:     *     * - `"change"` - The value of the field has changed     * - `"touch"` - The field has been touched     * - `"blur"` - The field has been blurred     * - `"submit"` - The form has been submitted     * - `"user"` - A user/developer has triggered the validation     */event:ValidateOn;})=>void|string[]|Promise<void|string[]>;};

Returns

typeFieldAtom<Value>=Atom<{/**   * An atom containing the field's name   */name:WritableAtom<string|undefined,[string|undefined|typeofRESET],void>;/**   * An atom containing the field's value   */value:WritableAtom<Value,[Value|typeofRESET|((prev:Value)=>Value)],void>;/**   * An atom containing the field's touched status   */touched:WritableAtom<boolean,[boolean|typeofRESET|((prev:boolean)=>boolean)],void>;/**   * An atom containing the field's dirty status   */dirty:Atom<boolean>;/**   * A write-only atom for validating the field's value   */validate:WritableAtom<null,[]|[ValidateOn],void>;/**   * An atom containing the field's validation status   */validateStatus:WritableAtom<ValidateStatus,[ValidateStatus],void>;/**   * An atom containing the field's validation errors   */errors:WritableAtom<string[],[string[]|((value:string[])=>string[])],void>;/**   * A write-only atom for resetting the field atoms to their   * initial states.   */reset:WritableAtom<null,[],void>;/**   * An atom containing a reference to the `HTMLElement` the field   * is bound to.   */ref:WritableAtom<HTMLInputElement|HTMLTextAreaElement|HTMLSelectElement|null,[|HTMLInputElement|HTMLTextAreaElement|HTMLSelectElement|null|((value:|HTMLInputElement|HTMLTextAreaElement|HTMLSelectElement|null,)=>HTMLInputElement|HTMLTextAreaElement|HTMLSelectElement|null),],void>;}>;

useField()

A hook that returnsstate andactions of a field atom fromuseFieldState anduseFieldActions.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseFieldOptions<Value>NoProvide aninitialValue here in additon to options that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks.

Returns

typeUseFieldAtom<Value>={/**   * Actions for managing the state of the field   */actions:UseFieldActions<Value>;/**   * The current state of the field   */state:UseFieldState<Value>;};

useInputField()

A hook that returnsprops,state, andactions of a field atom fromuseInputFieldProps,useFieldState,anduseFieldActions.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseInputFieldOptions<Type, Value>NoProvide aninitialValue here in additon to options that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks.

Returns

typeUseInputField<TypeextendsReact.HTMLInputTypeAttribute,ValueextendsInputFieldValueForType<Type>=InputFieldValueForType<Type>,>={/**   * `<input>` props for the field   */props:UseInputFieldProps<Type>;/**   * Actions for managing the state of the field   */actions:UseFieldActions<Value>;/**   * The current state of the field   */state:UseFieldState<Value>;};

useInputFieldProps()

A hook that returns a set of props that can be destructured directly into an<input> element.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseInputFieldPropsOptions<Type>NoAtype field and other options that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseInputFieldProps<TypeextendsReact.HTMLInputTypeAttribute>={/**   * The name of the field if there is one   */name:string|undefined;/**   * The value of the field   */value:TypeextendsDateType    ?string    :TypeextendsNumberType      ?number|string      :TypeextendsFileType        ?undefined        :string;/**   * The type of the field   *   *@default "text"   */type:Type;/**   * A WAI-ARIA property that tells a screen reader whether the   * field is invalid   */"aria-invalid":boolean;/**   * A React callback ref that is used to bind the field atom to   * an `<input>` element so that it can be read and focused.   */ref:React.RefCallback<HTMLInputElement>;onBlur(event:React.FormEvent<HTMLInputElement>):void;onChange(event:React.ChangeEvent<HTMLInputElement>):void;};

useTextareaField()

A hook that returnsprops,state, andactions of a field atom fromuseTextareaFieldProps,useFieldState,anduseFieldActions.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseTextareaFieldOptions<Value>NoProvide aninitialValue here in additon to options that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks.

Returns

typeUseTextareaField<Valueextendsstring>={/**   * `<input>` props for the field   */props:UseTextareaFieldProps<Value>;/**   * Actions for managing the state of the field   */actions:UseFieldActions<Value>;/**   * The current state of the field   */state:UseFieldState<Value>;};

useTextareaFieldProps()

A hook that returns a set of props that can be destructured directly into a<textarea> element.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseTextareaFieldPropsOptionsNoAtype field and other options that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseTextareaFieldProps<Valueextendsstring>={/**   * The name of the field if there is one   */name:string|undefined;/**   * The value of the field   */value:Value;/**   * A WAI-ARIA property that tells a screen reader whether the   * field is invalid   */"aria-invalid":boolean;/**   * A React callback ref that is used to bind the field atom to   * an `<input>` element so that it can be read and focused.   */ref:React.RefCallback<HTMLTextAreaElement>;onBlur(event:React.FormEvent<HTMLTextAreaElement>):void;onChange(event:React.ChangeEvent<HTMLTextAreaElement>):void;};

useSelectField()

A hook that returnsprops,state, andactions of a field atom fromuseSelectFieldProps,useFieldState,anduseFieldActions.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseSelectFieldOptions<Value, Multiple>NoProvide aninitialValue here in additon to options that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks.

Returns

typeUseSelectField<Valueextendsstring,MultipleextendsReadonly<boolean>=false,>={/**   * `<input>` props for the field   */props:UseSelectFieldProps<Value,Multiple>;/**   * Actions for managing the state of the field   */actions:UseFieldActions<Multipleextendstrue ?Value[] :Value>;/**   * The current state of the field   */state:UseFieldState<Multipleextendstrue ?Value[] :Value>;};

useSelectFieldProps()

A hook that returns a set of props that can be destructured directly into a<select> element.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseSelectFieldPropsOptions<Multiple>NoAtype field and other options that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseSelectFieldProps<Valueextendsstring,MultipleextendsReadonly<boolean>=false,>={/**   * The name of the field if there is one   */name:string|undefined;/**   * The value of the field   */value:Multipleextendstrue ?Value[] :Value;/**   * Whether the field is a multiple select   */multiple?:Multiple;/**   * A WAI-ARIA property that tells a screen reader whether the   * field is invalid   */"aria-invalid":boolean;/**   * A React callback ref that is used to bind the field atom to   * an `<input>` element so that it can be read and focused.   */ref:React.RefCallback<HTMLSelectElement>;onBlur(event:React.FormEvent<HTMLSelectElement>):void;onChange(event:React.ChangeEvent<HTMLSelectElement>):void;};

useFieldState()

A hook that returns the state of a field atom. This includes the field's value, whether it has been touched, whether it is dirty, the validation status, and any errors.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFieldState<Value>={/**   * The value of the field   */value:ExtractAtomValue<ExtractAtomValue<FieldAtom<Value>>["value"]>;/**   * The touched state of the field   */touched:ExtractAtomValue<ExtractAtomValue<FieldAtom<Value>>["touched"]>;/**   * The dirty state of the field. A field is "dirty" if it's value has   * been changed.   */dirty:ExtractAtomValue<ExtractAtomValue<FieldAtom<Value>>["dirty"]>;/**   * The validation status of the field   */validateStatus:ExtractAtomValue<ExtractAtomValue<FieldAtom<Value>>["validateStatus"]>;/**   * The error state of the field   */errors:ExtractAtomValue<ExtractAtomValue<FieldAtom<Value>>["errors"]>;};

useFieldActions()

A hook that returns a set of actions that can be used to interact with the field atom state.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFieldActions<Value>={/**   * A function that validates the field's value with a `"user"` validation   * event.   */validate():void;/**   * A function for changing the value of a field. This will trigger a `"change"`   * validation event.   *   *@param {Value} value - The new value of the field   */setValue(value:ExtractAtomArgs<ExtractAtomValue<FieldAtom<Value>>["value"]>[0],):void;/**   * A function for changing the touched state of a field. This will trigger a   * `"touch"` validation event.   *   *@param {boolean} touched - The new touched state of the field   */setTouched(touched:ExtractAtomArgs<ExtractAtomValue<FieldAtom<Value>>["touched"]>[0],):void;/**   * A function for changing the error state of a field   *   *@param {string[]} errors - The new error state of the field   */setErrors(errors:ExtractAtomArgs<ExtractAtomValue<FieldAtom<Value>>["errors"]>[0],):void;/**   * Focuses the field atom's `<input>`, `<select>`, or `<textarea>` element   * if there is one bound to it.   */focus():void;/**   * Resets the field atom to its initial state.   */reset():void;};

useFieldInitialValue()

A hook that sets the initial value of a field atom. Initial values can only be setonce per scope. Therefore, if the initial value used is changed during rerenders,it won't update the atom value.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
initialValueValueNoThe initial value to set the atom to. If this isundefined, no initial value will be set.
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

useFieldValue()

A hook that returns the value of a field atom.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFieldValue<Value>=Value;

useFieldErrors()

A hook that returns the errors of a field atom.

Arguments

NameTypeRequired?Description
fieldAtomFieldAtom<Value>YesThe atom that stores the field's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFieldErrors<Value>=UseFieldState<Value>["errors"];

Form atoms

formAtom()

An atom that derives its state fields atoms and allows you to submit,validate, and reset your form.

Arguments

NameTypeRequired?Description
fieldsFormFieldsYesAn object containing field atoms to be included in the form. Field atoms can be deeply nested in objects and arrays.

FormFields

typeFormFields={[key:string|number]:|FieldAtom<any>|FormFields|FormFields[]|FieldAtom<any>[];};

Returns

typeFormAtom<FieldsextendsFormFields>=Atom<{/**   * An atom containing an object of nested field atoms   */fields:WritableAtom<Fields,Fields|typeofRESET|((prev:Fields)=>Fields),void>;/**   * An read-only atom that derives the form's values from   * its nested field atoms.   */values:Atom<FormFieldValues<Fields>>;/**   * An read-only atom that derives the form's errors from   * its nested field atoms.   */errors:Atom<FormFieldErrors<Fields>>;/**   * A read-only atom that returns `true` if any of the fields in   * the form are dirty.   */dirty:Atom<boolean>;/**   * A read-only atom derives the touched state of its nested field atoms.   */touchedFields:Atom<TouchedFields<Fields>>;/**   * A write-only atom that resets the form's nested field atoms   */reset:WritableAtom<null,void>;/**   * A write-only atom that validates the form's nested field atoms   */validate:WritableAtom<null,void|ValidateOn>;/**   * A read-only atom that derives the form's validation status   */validateStatus:Atom<ValidateStatus>;/**   * A write-only atom for submitting the form   */submit:WritableAtom<null,(values:FormFieldValues<Fields>)=>void|Promise<void>>;/**   * A read-only atom that reads the number of times the form has   * been submitted   */submitCount:Atom<number>;/**   * An atom that contains the form's submission status   */submitStatus:WritableAtom<SubmitStatus,SubmitStatus>;}>;

useForm()

A hook that returns an object that contains thefieldAtoms and actions to validate, submit, and reset the form.

Arguments

NameTypeRequired?Description
formAtomFormAtom<Fields>YesThe atom that stores the form's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFormAtom<FieldsextendsFormFields>={/**   * An object containing the values of a form's nested field atoms   */fieldAtoms:Fields;/**   * A function for handling form submissions.   *   *@param handleSubmit - A function that is called with the form's values   *   when the form is submitted   */submit(handleSubmit:(values:FormFieldValues<Fields>)=>void|Promise<void>,):(e?:React.FormEvent<HTMLFormElement>)=>void;/**   * A function that validates the form's nested field atoms with a   * `"user"` validation event.   */validate():void;/**   * A function that resets the form's nested field atoms to their   * initial states.   */reset():void;};

useFormState()

A hook that returns the primary state of the form atom including values, errors, submit and validation status, as well as thefieldAtoms. Note that this hook will cuase its parent component to re-render any time those states change, so it can be useful to use more targeted state hooks likeuseFormStatus.

Arguments

NameTypeRequired?Description
formAtomFormAtom<Fields>YesThe atom that stores the form's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFormState<FieldsextendsFormFields>={/**   * An object containing the form's nested field atoms   */fieldAtoms:Fields;/**   * An object containing the values of a form's nested field atoms   */values:FormFieldValues<Fields>;/**   * An object containing the errors of a form's nested field atoms   */errors:FormFieldErrors<Fields>;/**   * `true` if any of the fields in the form are dirty.   */dirty:boolean;/**   * An object containing the touched state of the form's nested field atoms.   */touchedFields:TouchedFields<Fields>;/**   * The number of times a form has been submitted   */submitCount:number;/**   * The validation status of the form   */validateStatus:ValidateStatus;/**   * The submission status of the form   */submitStatus:SubmitStatus;};

useFormActions()

A hook that returns a set of actions that can be used to update the state of the form atom. This includes updating fields, submitting, resetting, and validating the form.

Arguments

NameTypeRequired?Description
formAtomFormAtom<Fields>YesThe atom that stores the form's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFormActions<FieldsextendsFormFields>={/**   * A function for adding/removing fields from the form.   *   *@param fields - An object containing the form's nested field atoms or   *   a callback that receives the current fields and returns the next   *   fields.   */updateFields(fields:ExtractAtomArgs<ExtractAtomValue<FormAtom<Fields>>["fields"]>[0],):void;/**   * A function for handling form submissions.   *   *@param handleSubmit - A function that is called with the form's values   *   when the form is submitted   */submit(handleSubmit:(values:FormFieldValues<Fields>)=>void|Promise<void>,):(e?:React.FormEvent<HTMLFormElement>)=>void;/**   * A function that validates the form's nested field atoms with a   * `"user"` validation event.   */validate():void;/**   * A function that resets the form's nested field atoms to their   * initial states.   */reset():void;};

useFormValues()

A hook that returns the values of the form atom.

Arguments

NameTypeRequired?Description
formAtomFormAtom<Fields>YesThe atom that stores the form's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFormValues<FieldsextendsFormFields>=FormFieldValues<Fields>;

useFormErrors()

A hook that returns the errors of the form atom.

Arguments

NameTypeRequired?Description
formAtomFormAtom<Fields>YesThe atom that stores the form's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFormErrors<FieldsextendsFormFields>=FormFieldErrors<Fields>;

useFormStatus()

A hook that returns thesubmitStatus andvalidateStatus of the form atom.

Arguments

NameTypeRequired?Description
formAtomFormAtom<Fields>YesThe atom that stores the form's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFormStatus={/**   * The validation status of the form   */validateStatus:ValidateStatus;/**   * The submission status of the form   */submitStatus:SubmitStatus;};

useFormSubmit()

A hook that returns a callback for handling form submission.

Arguments

NameTypeRequired?Description
formAtomFormAtom<Fields>YesThe atom that stores the form's state
optionsUseAtomOptionsNoOptions that are forwarded to theuseAtom,useAtomValue, anduseSetAtom hooks

Returns

typeUseFormSubmit<FieldsextendsFormFields>={(values:(value:FormFieldValues<Fields>)=>void|Promise<void>,):(e?:React.FormEvent<HTMLFormElement>)=>void;};

Components

<Form>

A React component that renders form atoms and their fields in an isolatedscope using a Jotai Provider.

Props

NameTypeRequired?Description
atomFormAtom<FormFields>YesA form atom
storeAtomStoreNoA Jotai store
componentReact.ComponentType<{state: UseFormState<Value>; actions: UseFormActions<Value>;}>NoA React component to render as the input field
render(state: UseFormState<Value>, actions: UseFormActions<Value>) => JSX.ElementNoA render prop

<InputField>

A React component that renders field atoms with initial values. This ismost useful for fields that are rendered as native HTML elements becausethe props can unpack directly into the underlying component.

Props

NameTypeRequired?Description
atomFieldAtom<Value>YesA field atom
initialValueValueNoThe initial value of the field
typeTypeNoThe type of the field. Defaults to"text".
storeAtomStoreNoA Jotai store
componentReact.ComponentType<{state: UseFieldState<Value>; actions: UseFieldActions<Value>;}>NoA React component to render as the input field
render(state: UseFieldState<Value>, actions: UseFieldActions<Value>) => JSX.ElementNoA render prop

<TextareaField>

A React component that renders field atoms with initial values. This ismost useful for fields that are rendered as native HTML elements becausethe props can unpack directly into the underlying component.

Props

NameTypeRequired?Description
atomFieldAtom<Value>YesA field atom
initialValueValueNoThe initial value of the field
storeAtomStoreNoA Jotai store
componentReact.ComponentType<{state: UseFieldState<Value>; actions: UseFieldActions<Value>;}>NoA React component to render as the input field
render(state: UseFieldState<Value>, actions: UseFieldActions<Value>) => JSX.ElementNoA render prop

<SelectField>

A React component that renders field atoms with initial values. This ismost useful for fields that are rendered as native HTML elements becausethe props can unpack directly into the underlying component.

Props

NameTypeRequired?Description
atomFieldAtom<Value>YesA field atom
initialValueValueNoThe initial value of the field
multiplebooleanNoIs this a multi-select field?
storeAtomStoreNoA Jotai store
componentReact.ComponentType<{state: UseFieldState<Value>; actions: UseFieldActions<Value>;}>NoA React component to render as the input field
render(state: UseFieldState<Value>, actions: UseFieldActions<Value>) => JSX.ElementNoA render prop

<Field>

A React component that renders field atoms with initial values. This ismost useful for fields that aren't rendered as native HTML elements.

Props

NameTypeRequired?Description
atomFieldAtom<Value>YesA field atom
initialValueValueNoThe initial value of the field
storeAtomStoreNoA Jotai store
componentReact.ComponentType<{state: UseFieldState<Value>; actions: UseFieldActions<Value>;}>NoA React component to render as the field
render(state: UseFieldState<Value>, actions: UseFieldActions<Value>) => JSX.ElementNoA render prop

Utilities

walkFields()

A function that walks through an object containing nested field atomsand calls a visitor function for each atom it finds.

Arguments

NameTypeRequired?Description
fieldsFormFieldsYesAn object containing nested field atoms
visitor(field: FieldAtom<any>, path: string[]) => void | falseYesA function that will be called for each field atom. You can exit early by returningfalse from the function.

Returns

void

Utility types

FormValues

A utility type for inferring the value types of a form's nested field atoms.

constnameForm=formAtom({name:fieldAtom({value:""}),});typeNameFormValues=FormValues<typeofnameForm>;

FormErrors

A utility type for inferring the error types of a form's nested field atoms.

constnameForm=formAtom({name:fieldAtom({value:""}),});typeNameFormErrors=FormErrors<typeofnameForm>;

form-atoms/valibot

createValibotValidator()

Validate your field atoms with Valibot schemas. This function validates on every"user" and"submit" event, in addition to other events you specify.

import{formAtom,fieldAtom}from"form-atoms";import{createValibotValidator}from"form-atoms/valibot";import{parseAsync,string,pipe,minLength}from"valibot";constvalibotValidate=createValibotValidator(parseAsync);//...constnameForm=formAtom({name:fieldAtom({validate:valibotValidate(pipe(string(),minLength(3,"uh oh")),{on:"submit",when:"dirty",}),}),});

form-atoms/zod

zodValidate()

Validate your field atoms with Zod schemas. This function validates on every"user" and"submit" event, in addition to other events you specify.

Check out an example on CodeSandbox

import{z}from"zod";import{formAtom,fieldAtom}from"form-atoms";import{zodValidate}from"form-atoms/zod";constschema=z.object({name:z.string().min(3),});constnameForm=formAtom({name:fieldAtom({validate:zodValidate(schema.shape.name,{on:"submit",when:"dirty",}),}),});

Arguments

NameTypeRequired?Description
schema((get: Getter) => z.Schema) | z.SchemaYesA Zod schema or a function that returns a Zod schema
configZodValidateConfigNoConfiguration options

ZodValidateConfig

typeZodValidateConfig={/**   * The event or events that triggers validation.   */on?:ZodValidateOn|ZodValidateOn[];/**   * Validate if the field is:   * - `touched`   * - `dirty`   */when?:"touched"|"dirty"|("touched"|"dirty")[];/**   * Format the error message returned by the validator.   *   *@param error - A ZodError object   */formatError?:(error:ZodError)=>string[];};

Wait, it's all atoms?

Wait it's all atoms? Always has been.


LICENSE

MIT


[8]ページ先頭

©2009-2025 Movatter.jp