0.2.2 • Published 4 years ago

@robertkirsz/useform v0.2.2

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

useForm

A React Hook for handling forms

npm install @robertkirsz/useform

Simplest usable example:

import useForm from '@robertkirsz/useform'

function App() {
  const form = useForm({
    initialValues: { firstName: 'Kasia' },
    onSubmit: values => { /* Do something with values */ }
  })

  return (
    <form onSubmit={form.handleSubmit}>
      <input {...form.inputs.firstName} />
      <button type="submit">Submit</button>
    </form>
  )
}

Validation:

const form = useForm({
  initialValues: { firstName: '' },
  validators = { firstName: value => value === '' && 'Value required' }
})

Warnings:

const form = useForm({
  initialValues: { comment: '' },
  warningValidators = { comment: value => value === '' && 'You sure you have nothing to say?' }
})

Setting values directly:

form.setValue('firstName', 'Marzena')

Triggering validation programatically:

form.validateField('firstName')
form.touchField('firstName')

We need to "touch" the field first, because "untouched" fields don't show validation statuses.

Setting validation errors directly:

form.setError('firstName', 'Name must be "Marzenka"!')
form.touchField('firstName')

Showing that the form is submitting:

For that, you need to return a Promise from your onSubmit function, like that:

function App() {
  const form = useForm({
    initialValues: { firstName: 'Kasia' },
    onSubmit: values => new Promise(resolve => {
      /* Do something with values, probably you want to send them to a server */
      resolve()
    })
  })

  return (
    <form onSubmit={form.handleSubmit}>
      <input {...form.inputs.firstName} />
      <button type="submit">
        {form.isSubmitting ? 'Submitting...' : 'Submit'}
      </button>
    </form>
  )
}
0.2.1

4 years ago

0.2.0

4 years ago

0.2.2

4 years ago

0.1.0

5 years ago