Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

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
/formPublic

A type-safe approach to managing complex form state in React.

License

NotificationsYou must be signed in to change notification settings

rzane/form

Repository files navigation

BuildVersionSizeLicense

A type-safe approach to managing complex form state in React.

This library provides integration with@stackup/validate to handle validation. However, it should be pretty easy to integrate whatever validation library you prefer.

You should also checkout@stackup/inputs, which includes some ready-made form fields.

Usage

importReactfrom"react";import{useForm,useField}from"@stackup/form";constForm=()=>{constform=useForm({initialValue:{email:"",name:""}});constvalidate=useValidation(form,value=>{if(value.email){return{valid:true, value};}else{return{valid:false,error:{email:"is required"}};}});constsubmit=useSubmit(validate,value=>{console.log(value);});return(<formonSubmit={submit}><Inputtype="email"label="Email"field={useField(form,"email")}/><Inputtype="text"label="Name"field={useField(form,"name")}/><buttontype="submit">Save</button></form>);};constInput=({  label,field:{ id, value, error, touched, setValue, setTouched},  ...props})=>(<div><labelhtmlFor={id}>{label}</label><input{...props}id={id}value={value}onBlur={useCallback(()=>setTouched(true),[])}onChange={useCallback(e=>setValue(e.target.value),[setValue])}/>{touched&&error&&<p>{error}</p>}</div>);

API

Table of Contents

useForm

Create a new form. A form requires an initial value, a function to validate,and a submit handler.

A form behaves just like any other field, but with some extra properties formanaging submission.

The initial value for the form can be literally anything! Usually, it's anobject, but it could be any type of value.

Parameters

Examples

Form values can be primitive

constform=useForm({initialValue:""});

But usually, they'll contain an object

constform=useForm({initialValue:{email:"",name:""}});

ReturnsForm<Value>

useField

Create a field for a given property.

Parameters

Examples

constform=useForm({initialValue:{email:"",profile:{name:""}}}});constemail=useField(form,"email");constprofile=useField(form,"profile");constname=useField(profile,"name");

ReturnsFormField<any>

useValidation

Use a plain ol' function for validation.

This hook can also be used to incorporate your favorite validation library.

Parameters

Examples

constvalidation=useValidation(form,value=>{if(!value.email){return{valid:false,error:{email:"can't be blank"}};}return{valid:true, value};});

ReturnsForm<Value, Result>

useValidate

Add validation to the form using@stackup/validate.

Parameters

Examples

constvalidator=schema({email:assert(isString).then(refute(isBlank))});constvalidate=useValidate(form,validator);

ReturnsForm<Value, Result>

useSubmit

Create a submit handler for the form.

Parameters

  • formForm<Value, Result>
  • fnSubmitFn<Result>
  • optsValidateOptions (optional, default{touch:true})

Examples

Sumbitting a form

constform=useForm({initialValue:"foo"});constsubmit=useSubmit(form,console.log);

Sumbitting with validation

constform=useForm({initialValue:"foo"});constvalidate=useValidate(form,myValidator);constsubmit=useSubmit(validate,console.log);

ReturnsSubmit

useReset

Create a reset handler for the form.

Parameters

  • formForm<Value, Result>

Examples

constform=useForm({initialValue:"foo"});constreset=useReset(form);

ReturnsReset

useFieldItem

Create a field for a specific index in an array.

This hook is intended for use in building forms with "Add another" functionality.

Parameters

Examples

constform=useForm({initialValue:{pets:[{name:""}]}});constpets=useField(form,"pets");constpet=useFieldItem(pets,0);constname=useField(pet,"name");

ReturnsFormField<Value>

usePushItem

Adds a new value to the end to an array of values.

This can be used to create a form with repeating fields.

Parameters

Examples

constpets=useField(form,"pets");constpet=useFieldItem(pets,0);constaddPet=usePushItem(pets,{name:""});

useInsertItem

Adds a new value at a specific position to an array of values.

This can be used to create a form with repeating fields.

Parameters

Examples

constpets=useField(form,"pets");constpet=useFieldItem(pets,0);constinsert=useInsertItem(pets,0,{name:""});

useRemoveItem

Removes a value at the given index from array of values.

This can be used to create a form with repeating fields.

Parameters

Examples

constpets=useField(form,"pets");constpet=useFieldItem(pets,0);constremovePet=useRemoveItem(pets,0);

useIdentifier

Creates a unique identifier that will remain consistent across re-renders.

This hook does not currently support SSR.

Parameters

Returnsstring

Form

Extends FormField<Value>

The value returned byuseForm.

initialValue

The initial values for the form.

Type: Value

initialError

The initial errors on the fields.

Type: FormError<Value>

initialTouched

The initially touched fields.

Type: FormTouched<Value>

setValidating

Indicate that the form is validating

Type: SetState<boolean>

setSubmitting

Indicate that the form is validating

Type: SetState<boolean>

setSubmission

Update the form's submission status

Type: SetState<Submission>

reset

Reset the state of the form

Type: function (opts: ResetOptions<Value>): void

validate

Run validation

Type: function (opts: ValidateOptions):Promise<ValidationResult<Value, Result>>

FormField

The primary form data structure.

id

A unique ID for this form field. This can be used to associate fields with a label.

Type:string

name

The name or array index that was given touseField oruseFieldItem.

Type: (string |number)

value

The current value of the field.

Type: Value

error

An error or errors that are associated with this field or it's children.

Type: FormError<Value>

touched

Indicates that this field or it's children have been modified by the user.

Type: FormTouched<Value>

isValidating

Indicates that validation is currently being run

Type:boolean

isSubmitting

Indicates that the form is currently being submitted

Type:boolean

submission

Keeps track of the form's submission status

Type:Submission

setValue

Change the value. Just like withsetState, you can pass a callbackto this function to get the current value and update it.

Type: SetState<Value>

setError

Update the error.

Type: SetState<FormError<Value>>

setTouched

Indicate that this field has been touched. This is usually called inonBlur.

Type: SetState<FormTouched<Value>>

ValidateFn

A function used for validation. This function must indicate whetheror not the form is valid.

Theerror property can be used to set errors on the form.

Thevalue property can be used to transform the form's values beforevalidation.

Type: function (value: Value): (ValidationResult<Value, Result> | PromiseLike<ValidationResult<Value, Result>>)

Submit

Submits the form.

Type: function (event: FormEvent<HTMLFormElement>):Promise<void>

Submission

Keeps track of submissions.

count

The number of times the form has been submitted

Type:number

error

If the submission flow throws an error, it will appear here.

Type:Error

Reset

Resets the form.

Type: function (event: FormEvent<HTMLFormElement>):Promise<void>

UseFormOptions

The options that can be passed touseForm.

id

Customize the base ID for all fields.

Type:string

initialValue

The initial values for the form.

Type: Value

initialError

The initial errors on the fields.

Type: FormError<Value>

initialTouched

The initially touched fields.

Type: FormTouched<Value>

UseValidationOptions

Configures when validation runs.

onChange

Enables validation whenever values change.

Type:boolean

onBlur

Enables validation whenever a field is touched.

Type:boolean

About

A type-safe approach to managing complex form state in React.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp