@uneksija/useform

0.3.4 • Public • Published

useform

React hook for simple form control

npm (scoped) GitHub

Installation

npm install @uneksija/useform

Importing the hook

import useForm from '@uneksija/useform'

Example usage

function validate({ age }) {
  if (age < 18) return { age: '18+ only' }
}

function App() {
  const { values, errors, isValid, handleChange, handleSubmit } = useForm({
    validate,
    initialValues: {
      name: 'john',
      age: 23
    },
    onSubmit: console.log
  })

  return (
    <form onSubmit={handleSubmit}>
      <label>
        name
        <input
          name="name"
          type="text"
          value={values.name}
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        age
        <input
          name="age"
          type="number"
          value={values.age}
          onChange={handleChange}
        />
        {errors.age}
      </label>
      <br />
      <button type="submit" disabled={!isValid}>
        save
      </button>
    </form>
  )
}

Arguments

Argument Description
initialValues Object containing the form initial values
onSubmit Function called with the values on form submit
validate Validate function, returns an object of error messages

Return object

Key Description
values Form values
errors Error messages
isValid Flag indicating if there are any errors
handleChange OnChange handler, input name needs to match value key
handleSubmit OnSubmit handler

Readme

Keywords

Package Sidebar

Install

npm i @uneksija/useform

Weekly Downloads

0

Version

0.3.4

License

MIT

Unpacked Size

7.79 kB

Total Files

5

Last publish

Collaborators

  • huijari
  • vihainen