another-use-form-hook
A React hook 🎣 for easy form handling
Table of Contents
Installation
This should be installed as one of your project dependencies
:
yarn add another-use-form-hook
or
npm install --save another-use-form-hook
NOTE:
another-use-form-hook
only works with react >=16.8, since it is a hook.
Usage
This hook is intended to give a full solution for handling forms. From interdependent field value validations (meaning if a field value is dependent on other field value), to submitting the form, and providing information about when the UI should be unresponsive (loading of some kind of async-like operation), in addition to notification "hooks" to be able to inform the users the most efficient way.
To retrieve props for an input field, you have the following options:
- Using the
form.inputs.{inputType}('name')
input prop generator function (inputTypes
is one of these) - Using
form.fields.{name}.{value|error}
andform.handleChange
functions
NOTE: The example below is available live at CodeSandbox
Let's see a complex example to understand how it works:
import React from "react";import ReactDOM from "react-dom";import useForm from "another-use-form-hook";import "./styles.css";/** * NOTE: We are using date-fns for this example, * but it is absolutly not a requirement. */import addDays isAfter differenceInDays parseISO from "date-fns";const isValidEmail = /\w*@\w*\.\w*/; // Do better 💩 const TODAY = ; const App = const form = ; return <form => /* option 1 (control all the props with a one-liner)*/ <fieldset> <legend>Option 1</legend> <label ="email"> formfieldsemailerror ? "Invalid" : "" email </label> <input /> <label ="departure"> formfieldsarrivalerror ? "Invalid" : "" arrival </label> <input // = /> </fieldset> /* option 2 specify id, type, name, value props manually*/ <fieldset> <legend>Option 2</legend> <label ="arrival"> formfieldsarrivalerror ? "Invalid" : "" arrival </label> <input ="date" ="arrival" ="arrival" = = /> <label ="departure"> formfieldsdepartureerror ? "Invalid" : "" departure </label> <input ="date" ="departure" ="departure" = = /> </fieldset> /* also from option 1 */ <button => Submit </button> </form> ;; ReactDOM;
Documentation
useForm
useFormuseFormParams: UserFormParams: UseForm
UseFormParams
name | type | description |
---|---|---|
name | string |
Refer to one of the forms in formProviderProps |
initialState | object |
See InitialState |
validators | function |
See Validators |
onSubmit | function |
See SubmitCallback |
onNotify | function |
See NotifyCallback |
InitialState
An object containing the default value of every field in a form.
Example:
If name
is defined, you can refer to initialStates.{name}
in formProviderProps.
Example:
//...<FormProvider =>//...const form = console // email@example.com
Validators
This function is invoked before onChange and onSubmit. The former only runs the validations for the changed fields, while the latter runs it on the whole form. For convenience, it is also returned from useForm
.
name | type | description |
---|---|---|
fields | object |
An object with the same shape as initialState |
submitting | boolean |
Set to true , when called before handleSubmit |
validations | object |
See Validations |
Validations
An object containing boolean
expressions. Each input field must have at least a corresponding property in this object, but you can define custom ones as well.
Example:
email: submitting ? : typeof fieldsemail === "string"
You can also look at the live example.
SubmitCallback
Invoked when handleSubmit is called and there were no validation issues.
name | type | description |
---|---|---|
name | string |
Same as name in useFormParams |
fields | object |
Validated fields, same shape as initialState |
setLoading | function |
Sets the returned loading property of useForm |
notify | function |
See NotifyCallback |
NotifyCallback
Invoked if there is a validation error when calling handleChange
or handleSubmit
. Can be manually triggered on onSubmit
by calling notify
.
name | type | description |
---|---|---|
type | string |
Type of notification |
reason | any |
When type is validationErrors , it is a list of field names, Otherwise you set it to whatever you want. |
Example:
Look at the live example.
UseFormReturn
name | type | description |
---|---|---|
name | string |
Same as in useFormParams. |
fields | object |
See FieldValuesAndErrors |
hasErrors | boolean |
For convenience. true if any of the returned fields.{name}.error is true . |
handleChange | function |
See ChangeHandler |
handleSubmit | function |
See SubmitHandler |
loading | boolean |
Controlled by setLoading in onSubmit |
inputs | object |
See InputPropGenerators |
validators | function |
See Validators |
FieldValuesAndErrors
Validated field values and their errors.
Example:
const form = console // { // email: { // value: "email@example.com", // error: false // }, // age: { // value: -2, // error: truefields // } // } console // true
ChangeHandler
You can call this two ways. Either pass an event as the first argument, or a partial fields
object. With the latter, you can change multiple values at the same time. E.g.: resetting the form after submit, or any other reason you might have.
name | type | description |
---|---|---|
event | React.FormEvent |
Standard event. Using target.{name\|value\|checked} to infer the intention |
fields | object |
Pass a partial fields object, if you want to change multiple values at the same time |
validations | string[] |
Which validators you would like to run. If omitted, only validators with the same event/field name will be run |
Example:
Look at the live example.
SubmitHandler
Call to submit the form. Before onSubmit is invoked, validators is run for every form field. If there were any errors, notify is invoked with type
being validationErrors
, and reason
a list of form field names.
InputPropGenerators
An object, containing properties with the same name as the HTML input types, with some minor differences.
For convenience, since datetime-local
contains a hyphen (-) character, it is also exposed as datetimeLocal
, to overcome the need of "
characters, when accessing it.
I.e.:
const form = forminputsdatetimeLocal == forminputs"datetime-local"
In addition to the standard input types, there is a select
type also available.
Each property is a function:
name | type | description |
---|---|---|
name | string |
The name of a field. Same as the properties of initialState |
options | object |
See InputTypeOptions |
Example:
For examples of all types, you can check this test suite
InputTypeOptions
An optional object
name | type | description |
---|---|---|
value | string |
Usually, when using radio buttons, values are static. (Each button in the same group must have different values) |
generateProps | function |
Provides name , value and error that can be used to generate additional props. Useful, if you want to avoid using form.fields |
formName | string |
If the input type is submit , it can be used to override the name of the form being submitted. |
Example:
const form = // *click on option-2*console // option-2return <radiogroup> <input /> <input /> /*You can do it the "traditional" way also*/ <input ='option-3' /> </radiogroup>
const form = return <div> <input /> /*Tip: if your custom Input component takes an error prop, you can try this: */ <Input /> /* This will spread error to Input as well.*/ /*Or here is a more complex example for a custom Input component*/ <Input /> </div>
InputPropGeneratorsReturn
An object that can be spread on a React input like element.
name | type | description |
---|---|---|
name | string |
The name of a field. Must be one of the properties in initialState |
id | string |
By default, same as name . If input type is radio , it is the same as value , to avoid problems in radio groups where id would be the same |
value | any |
The value of the field |
onChange | function |
See onChange |
checked | boolean |
If input type is checkbox , it is the same as value |
onClick | function |
If input type is submit , it is onSubmit |
Example:
const form = return <div> <label ="emailField">E-mail</label> <input /> /* This is the same as */ <input ="emailField" ="emailField" ="email" = = /> </div>
FormProvider
FormProviderProps
name | type | description |
---|---|---|
initialStates | object |
Single place to define all initialState for every form. See InitialState |
validators | object |
Single place to define all validators for every form. See Validators |
onSubmit | function |
Same as onSubmit |
onNotify | function |
Same as onNotify |
children | ReactElement |
The element you would like to wrap with FormProvider |
getForms
Forms
An object containing all the forms' current values in FormProvider. Same shape as initialStates
.
LICENSE
MIT