import { useForm } from 'react-form'
const instance = useForm(options)
defaultValues: any
- Use defaultValues to set the default values state for the form. If this object ever changes, the state will be reset to the new object. Thus, its important to use React.useMemo to make this object only change when necessary
onSubmit(values, instance) => Promise
onSubmit
is called when the form's Form element is submitted or wheninstance.handleSubmit
is called.values
is the submitted values object for the forminstance
is the latest version of the form instance (the same instance that is returned fromuseForm
)- If the promise returned from this function resolves,
instance.isSubmitted
will be set totrue
- When the promise returned from this function settles,
instance.isSubmitting
will be set tofalse
validate async (values, instance) => String | false | undefined
validate
is an asynchronous function that is called when the form becomes dirty and is given the opportunity to set/clear/update errors and/or manage general form stateinstance
is the latest version of the form instance (the same instance that is returned fromuseForm
)- See below for more information on form validation
- Field level validation is also available. See
useField
validatePristine: Bool
- If you want validation to run when instance.isDirty is false, you can set the
validatePristine
option totrue
- If you want validation to run when instance.isDirty is false, you can set the
debugForm: Bool
- If set to
true
the form instance will be serialized and rendered after theForm
element returned by the instance
- If set to
An object
with the following components, properties and methods:
-
Form: ReactComponent<form>
- Required
- This component is a ready-to-use wrapper around the html
form
element. - It will proxy any props you pass it, excluding
onSubmit
.- It properly supplies the form context to any
useField
instances inside it.
- It properly supplies the form context to any
-
values: any
- The current values for the entire form
-
meta: Object
error: String | any
- If an error is returned by the form's
validation
function, or if it is set programmatically, it will be stored here.
- If an error is returned by the form's
isSubmitting: Bool
- Will be set to
true
if the form is currently submitting
- Will be set to
isDirty: Bool
- Will be set to
true
if the form is dirty
- Will be set to
isSubmitted: Bool
- Will be set to
true
if the form has been submitted successfully
- Will be set to
submissionAttempts: Int
- Will be incremented, starting from
0
, every time a form submission is attempted
- Will be incremented, starting from
isValid: Bool
- Will be set to
true
ifisDirty === true
andisValid === true
, meaning that the form has been touched and there are no field-level or form-level errors
- Will be set to
fieldsAreValidating
- Will be
true
if there are any fields validating (field.meta.isValidating
)
- Will be
fieldsAreValid
- Will be
true
if there are no fields with an error (field.meta.error
)
- Will be
isValid
- Will be
true
if every field is valid and there is no form error (instance.meta.allFieldsValid && !instance.meta.error
)
- Will be
canSubmit: Bool
- Will be
true
if the form is valid and not in the middle of a submission attempt (instance.meta.isValid && !instance.meta.isSubmitting
) - This can be used to enable/disable a submit button for the form.
- Will be
...any
- Any other meta information can be stored here via the
field.setMeta
orinstance.setFieldMeta
functions
- Any other meta information can be stored here via the
-
formContext: FormInstance
- This can be used to manually link
useField
instances to a parent form. This is useful ifuseField
is in the same block scope asuseForm
. - Simply pass
formContext
touseField
like so:useField(fieldName, { formContext })
. That field is now linked to the form that provided theformContext
.
- This can be used to manually link
-
reset() => void
- This function will reset the form's state, and set
instance.values
to thedefaultValues
option
- This function will reset the form's state, and set
-
setMeta((updater(previousMeta: Object) => newMeta: Object) | newMeta: Object)
- Use this function to update the form's
meta
value. - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's
setState
callback style. - Unlike React's setState pattern though, if a new object is passed, it will NOT replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above.
- Use this function to update the form's
-
handleSubmit(formSubmitEvent) => void
- This function is used to submit the form.
- It is automatically called when using the
Form
component returned byuseTable
. - If you build your form using your own
form
element, this function is required and should be set as the callback to theform
via theonSubmit
prop
-
debounce(Function, wait: Int) => Promise
- This function can be used to debounce any function at the specified wait time. Calls to this function will be deduped per form-instance.
- Typically, this function is used in the
validate
callback to control validation timing and flow - A new promise is returned for each call to this function
- Over the course of multiple overlapping calls to this function, only the latest active promise that both fires and finishes will actually resolve or reject. In other words, if you call this function before a previous call to it resolves, all previous calls will be discarded and never resolve or reject so as to avoid unwanted side effects from stale promises. Turns out this is easier than cancelling promises :)
-
setValues(updater(previousValues: Object) => newValues: Object) | newValues: Object
- Use this function to update the form's
meta
value. - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's
setState
callback style. - If a value is passed, it will replace the entire values object, similar to React's
setState
callback style.
- Use this function to update the form's
-
runValidation() => void
- Use this function to manually run the form-level validation.
- This function does not run validation for fields. If that is a requirement you have, the please file a feature request and I'll make it happen.
-
getFieldValue(fieldPath: String) => any
- This function returns the
value
from the form'sinstance.values
object located at thefieldPath
string that was passed. fieldPath
is a string that supports object notation, eg.foo[3].bar[1].baz
- This function returns the
-
getFieldMeta(fieldPath: String) => Object: { error: String | null, ...any }
- This function returns a field's
meta
object from the form. fieldPath
is a string that supports object notation, eg.foo[3].bar[1].baz
- This function returns a field's
-
setFieldValue(fieldPath: String, (updater(previousValue: any) => newValue: any) | newValue: any, options: Object { isTouched: Bool } )
- Use this function to update a field's corresponding
value
that is stored in theinstance.values
object. - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's
setState
callback style. - Unlike React's setState pattern though, if a new object is passed, it will NOT replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above.
- Optionally, an
options
object can be passed.isTouched: Bool
- Defaults to
true
- If set to
false
, this operation will not trigger the field'sisTouched
to automatically be set totrue
- Defaults to
- Use this function to update a field's corresponding
-
setFieldMeta(fieldPath: String, (updater(previousMeta: Object) => newMeta: Object) | newMeta: Object)
- Use this function to update a fields
meta
value. - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's
setState
callback style. - Unlike React's setState pattern though, if a new object is passed, it will NOT replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above.
- Use this function to update a fields
-
pushFieldValue(fieldPath: String, newValue: any)
- Use this function to push a new value into a field that has an array-like value.
- An error will be thrown if the field's current value is not an array.
-
insertFieldValue(fieldPath: String, insertIndex: Int, value: any)
- Use this function to insert a new value into a field that has an array-like value at the specified index.
- An error will be thrown if the field's current value is not an array.
-
removeFieldValue(fieldPath: String, removalIndex: Int)
- Use this function to remove a value from a field that has an array-like value at the specified index.
- An error will be thrown if the field's current value is not an array.
-
swapFieldValues(fieldPath: String, firstIndex: Int, secondIndex: Int)
- Use this function to swap two values inside of a field that has an array-like value at the specified indices.
- An error will be thrown if the field's current value is not an array.
import { useField } from 'react-form'
const fieldInstance = useField(fieldPath, options)
fieldPath: String
- Required
- The path the value for this field.
- Supports deeply nested object notation, eg.
foo[3].bar[1].baz
- Any integers that can be reliably detected between notation boundaries will be treated as array indices:
1
,[1]
,1.
,.1.
or.1
options
- An optional object to configure the fielddefaultValue: any
- Use
defaultValue
to set the defaultvalue
state for the field. - If this object ever changes, the field meta will be reset to the new value. Thus, its important to use
React.useMemo
to make this object only change when necessary
- Use
defaultError: String | undefined
- Use
defaultError
to set the defaulterror
state for the field. - If this object ever changes, the field meta will be reset to the new value. Thus, its important to use
React.useMemo
to make this object only change when necessary
- Use
defaultIsTouched: Bool | undefined
- Use
defaultIsTouched
to set the defaultisTouched
state for the field. - If this object ever changes, the field meta will be reset to the new value. Thus, its important to use
React.useMemo
to make this object only change when necessary
- Use
defaultMeta: Object | undefined
- Use
defaultMeta
to set any additional defaultmeta
state for the field. - Unlike
defaultValue
,defaultError
anddefaultIsTouched
, changing this object will not trigger the field meta to be updated. It is only updated when theuseField
hook mounts andmeta
for that field has not yet been initialized (meta === undefined
)
- Use
validate async (value, instance) => String | false | undefined
validate
is an asynchronous function that is called when the field becomes dirty and is given the opportunity to set/clear/update errors and/or manage general field metainstance
is the latest version of the field instance (the same instance that is returned fromuseField
)- See below for more information on field validation
- Form level validation is also available. See
useForm
filterValue: (value, instance) => newValue
- The
filterValue
function is used to manipulate new values before they are set viafield.setValue
andinstance.setFieldValue
. - This is useful for restricting fields to specific values, eg. min/max, length, regex replacement, disallowing invalid values (as opposed to warning about them), among limitless others.
- The
validatePristine: Bool
- If you want validation to run when instance.isDirty is false, you can set the
validatePristine
option totrue
- If you want validation to run when instance.isDirty is false, you can set the
An object
with the following components, properties and methods:
form: FormInstance
- The root form
instance
- The root form
fieldName: String
- The full fieldName (from the root of the form) for this field
value: any
- The current value of this field
meta: Object {}
error: String | any
- If an error is returned by the field's
validation
function, or if it is set programmatically, it will be stored here.
- If an error is returned by the field's
isTouched: Bool
- Will be set to
true
if the field has been touched.
- Will be set to
...any
- Any other meta information can be stored here via the
field.setMeta
orinstance.setFieldMeta
functions
- Any other meta information can be stored here via the
FieldScope: ReactComponent<Provider>
- Optional
- This component does not render any markup
- It set the new base field scope to this field's
fieldpath
- It supplies this new base field scope, along with the form scope to any
useField
instances inside it. - Any
useField(fieldPath)
instances used insde ofFieldScope
will inherit this field'sfieldPath
as a parent. - See Field Scoping for more information
debounce(Function, wait: Int) => Promise
- This function can be used to debounce any function at the specified wait time. Calls to this function will be deduped per
useField
instance. - Typically, this function is used in the
validate
callback to control validation timing and flow - A new promise is returned for each call to this function
- Over the course of multiple overlapping calls to this function, only the latest active promise that both fires and finishes will actually resolve or reject. In other words, if you call this function before a previous call to it resolves, all previous calls will be discarded and never resolve or reject so as to avoid unwanted side effects from stale promises. Turns out this is easier than cancelling promises :)
- This function can be used to debounce any function at the specified wait time. Calls to this function will be deduped per
runValidation() => void
- Use this function to manually run this field's validation.
- This function does not run validation for fields.
getInputProps(props: Object {}) => enhanced props Object
onChange: ChangeEventHandler
onBlur: FormEventHandler
...rest
- any other props that will be spread into the enhanced props- Use this function to set props on input elements. If set,
onChange
andonBlur
will be wrapped to update the fieldvalue
. - The enhanced props will always contain
value
,onChange
, andonBlur
. Any of the rest that are passed in will also be returned.
The following methods do not require the use of a fieldPath
. This field's fieldPath
will automatically be used.
-
setValue((updater(previousValue: any) => newValue: any) | newValue: any, options: Object { isTouched: Bool } )
- Use this function to update a field's corresponding
value
that is stored in theinstance.values
object. - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's
setState
callback style. - Unlike React's setState pattern though, if a new object is passed, it will NOT replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above.
- Optionally, an
options
object can be passed.isTouched: Bool
- Defaults to
true
- If set to
false
, this operation will not trigger the field'sisTouched
to automatically be set totrue
- Defaults to
- Use this function to update a field's corresponding
-
setMeta((updater(previousMeta: Object) => newMeta: Object) | newMeta: Object)
- Use this function to update a fields
meta
value. - If a callback is passed, it will be given the previous value and be expected to return a new one, similar to React's
setState
callback style. - Unlike React's setState pattern though, if a new object is passed, it will NOT replace the meta object entirely. Since this is a common use case, it will be shallowly merged. If you need to replace the entire meta object, please use the functional callback style above.
- Use this function to update a fields
-
pushValue(newValue: any)
- Use this function to push a new value into a field that has an array-like value.
- An error will be thrown if the field's current value is not an array.
-
insertValue(insertIndex: Int, value: any)
- Use this function to insert a new value into a field that has an array-like value at the specified index.
- An error will be thrown if the field's current value is not an array.
-
removeValue(removalIndex: Int)
- Use this function to remove a value from a field that has an array-like value at the specified index.
- An error will be thrown if the field's current value is not an array.
-
swapValues(firstIndex: Int, secondIndex: Int)
- Use this function to swap two values inside of a field that has an array-like value at the specified indices.
- An error will be thrown if the field's current value is not an array.
The following methods are almost exactly the same as their top-level form instance
counterparts, except for any fieldPath
that is passed to them will be prefixed with this field's fieldPath
For example, if our field had the fieldPath
of foo
, then setFieldValue('[0]', true)
would be similar to calling instance.setFieldValue('foo[0]', true)
setFieldValue(subFieldPath, ...)
- See Form InstancesetFieldMeta(subFieldPath, ...)
- See Form InstancepushFieldValue(subFieldPath, ...)
- See Form InstanceinsertFieldValue(subFieldPath, ...)
- See Form InstanceremoveFieldValue(subFieldPath, ...)
- See Form InstanceswapFieldValues(subFieldPath, ...)
- See Form Instance
If you get into a situation where you need to use useForm
and useField
in the same block scope, you may see a missing form context error. This is because your useField
usage is not inside of a <Form>
component. To get around this error for this use case, you can pass the form's instance.formContext
value to the useField
options to manually link them together:
function App() {
const { Form, formContext } = useForm()
// This field will now be manually linked to the form above
const fieldInstance = useField('age', {
formContext,
})
return <Form>...</Form>
}
A utility function for filter React-Form-related props from an object.
import { splitFormProps } from 'react-form'
function TextField(props) {
const [field, options, rest] = splitFormProps(props)
// options === {
// defaultValue,
// defaultIsTouched,
// defaultError,
// defaultMeta,
// validatePristine,
// validate,
// onSubmit,
// defaultValues,
// debugForm,
// }
const fieldInstance = useField(field, options)
return <input {...rest} />
}
A hook for gaining access to the form state from within a Form
component
import { useFormContext } from 'react-form'
function App() {
const { Form } = useForm()
return (
<Form>
<Stuff />
</Form>
)
}
function Stuff() {
const formInstance = useFormContext()
console.log(formInstance)
}