Table of Contents
- Getting Started
- Examples
- API
- Contributing
- Versioning
- Authors
- About us
- License
To get it started, add use-form-state
to your project:
npm install --save use-form-state
Please note that use-form-state
requires react@^16.12.0
as a peer dependency.
import useFormState from 'use-form-state'
export const LoginForm = ({ onSubmit }) => {
const { getNativeInputProps } = useFormState()
return (
<form onSubmit={onSubmit}>
<input {...getNativeInputProps('email')} required />
<input {...getNativeInputProps('password')} required />
</form>
)
}
From the example above, as the user submits the form, the formState
object will look something like this:
{
values: {
email: '[email protected]',
password: '123456789',
},
errors: [],
isDirty: true
isValid: true,
isPristine: false,
setValues: Function,
handleChange: Function,
handleNativeChange: Function,
validate: Function,
updateErrors: Function,
resetForm: Function,
getInputProps: Function,
getNativeInputProps: Function,
valuesToInput: Function,
getValue: Function,
getErrorMessages: Function,
hasError: Function,
}
import useFormState from 'use-form-state'
export const FormComponent = () => {
const {
values,
errors,
isDirty,
isValid,
isPristine,
setValues,
handleChange,
handleNativeChange,
validate,
updateErrors,
resetForm,
getInputProps,
getNativeInputProps,
valuesToInput,
getValue,
getErrorMessages,
hasError,
} = useFormState(initialValues, formOptions)
return (
// ...
)
}
useFormState
takes an optional initial values object with keys as the name property of the form inputs, and values as the initial values of those inputs.
useFormState
also accepts an optional form options object as a second argument with following properties:
Function that returns an array of validators created by createFormValidation
Example: See return value of createFormValidation
Default: empty array
Adds extra options that can be used in the validation. See validate.validationOptions for more info
Example:
const isCompany = user.type === 'company'
const formState = useFormState(initialValues, {
validationOptions: {
isCompany,
}
})
Default: empty object
Function that can be used to manipulate the values used in the form state before submitting the form. This can be useful when the name of the input field differs from the API or when you need to parse/format dates for example.
Example:
const formState = useFormState(initialValues, {
valuesToInput: ({
firstName,
birthDate,
...otherValues,
}) => ({
...otherValues,
first_name: firstName,
birth_date: birthDate.toISOString(),
})
})
Default: values from state
When set to true
, useFormState
will log its state to the console when changes are made.
Default: false
import useFormState, { createFormValidation } from 'use-form-state'
export const FormComponent = () => {
const formState = useFormState(initialValues, {
validation: createFormValidation([{
path: 'firstName',
validate: (name) => name !== '',
message: 'First name is required!',
}, {
path: 'birthDate',
validate: (date) => date > new Date(),
message: 'Date must be after now.',
}, {
path: 'vatNumber',
validate: (vatNumber, values, { isCompany }) => (
isCompany && vatNumber !== ''
),
message: 'VAT number is required for a company.',
}])
})
return (
// ...
)
}
Required
path
references the name to the value in the formState where you want to add the validation on.
Required
Function that validates the given value and returns the result of the expresion.
The first argument of validate
is the value from the formState based on the given path
.
Second argument includes all the values from the formState.
validationOptions
is an optional argument you can use as external "dependency" for your validation expression.
The message
you want to display near the form input to show the user what went wrong.
Default: 'Invalid'
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
We use SemVer for versioning. For the versions available, see the tags on this repository.
- Sander Peeters - Initial work - Sander Peeters
See also the list of contributors who participated in this project.
Wappla BVBA We shape, build and grow ambitious digital products.
This project is licensed under the MIT License - see the LICENSE.md file for details