use-managed-form is a custom React hook designed to streamline controlled form handling. It provides intuitive state management, and dynamic validations, making it effortless to build interactive and customizable forms with minimal complexity.
npm install use-managed-formEasily manage your React forms with 'use-managed-form', a custom hook that
simplifies state handling and validations for creating interactive and dynamic
forms.
Install the package via npm:
``bash`
npm install use-managed-form
Or using bun:
`bash`
bun add use-managed-form
Or using yarn:
`bash`
yarn add use-managed-form
First, import the hook:
`javascript`
import useForm from 'use-managed-form'
Define your initial state for the form fields:
`javascript`
const initialFormState = {
email: '',
password: ''
}
Then, initialize the hook:
`javascript`
const { form, onChange } = useForm(initialFormState)
The useForm hook provides the following:
- : the value of the input field with the corresponding key in theform
initial state object.
- : an object with the following properties:
- :id
- : the input key.value
- : the current value of the input.error
- : the current validation error associated to the input.reset
- : a function that resets all form fields to their initial values andclearErrors
clears all validation errors.
- : a function that clears all validation errors withoutisValid
resetting the field values.
- : a function that returns a boolean value indicating whether thereonChange(e: React.ChangeEvent
are any validation errors or not.
- :setValue(key, value)
an event handler that updates the value of a form field when the user
interacts with it.
- : Manually update a specific input value.setError(key, error)
- : Attach an error message to an input.setEntries(entries)
- : Manually update all input values, where entries should
be of the same shape as the initial state object.
`javascript
import React from 'react'
import useForm from 'use-managed-form'
const MyForm = () => {
const { form, onChange, setError } = useForm({
email: '',
password: ''
})
const submitAction = () => {
console.log('After validation')
// after submit action
form.reset()
}
const handleSubmit = (event) => {
event.preventDefault()
form.clearErrors()
if (!form.email.value) setError(form.email.id, 'Email is required')
if (!form.password.value) setError(form.password.id, 'Password is required')
if (!form.isValid()) {
console.log('Please fix all the errors')
return
}
submitAction()
}
return (
export default MyForm
`
You could also extract each input value individually:
`javascript`
const { email, password, form, onChange } = useForm({
email: '',
password: ''
})
For boolean values (e.g., checkboxes):
`javascript
const { form, onChange } = useForm({
rememberMe: false
})
; type='checkbox'
name='rememberMe'
checked={form.rememberMe.value}
onChange={onChange}
/>
``
Contributions are welcome! Check out the source code on
GitHub. Feel free to open
issues or submit pull requests.
This package is also available on
npm.