1.0.7 • Published 3 years ago

react-better-hook-form v1.0.7

Weekly downloads
319
License
MIT
Repository
-
Last release
3 years ago

React Better Hook Form

React Better Hook Form is a custom hook that helps you handle easier the form submission.

How to install

npm install react-better-hook-form

OR

yarn add react-better-hook-form

How to use

1. Import the hook:

import { useForm } from "react-better-hook-form"

2. Create a function:

function Form() {
    // ...
}

3. Destructure the hook:

function Form() {
    const { handleChange, checkErrors, errors, data } = useForm()
    // ...
}

The hook accept an object as parameter. The object can contains 2 properties:

  • default - the default value of data
default: { 
    property: value
}
  • reqs - requirements for every field
reqs: {
  inputName: {
    required: true || "Error message", // if required is true, the message will be [inputName] is required
    email: true || "Error message", // if email is true, the message will be [inputName] is not a valid email
    min:  number || {
      value: number,
      message: "Error message"
    }, // if min is of type number, the error message will be "[inputName] is too short"
    max:  number || {
      value: number,
      message: "Error message"
    } // if max is of type number, the error message will be "[inputName] is too long"
  }
}

EXAMPLE

useForm({
  default: {
    username: "guest"
  }, reqs:  {
    username:  {
      required: true,
      min: 8,
      max: {
        value: 32,
        message: "Maximum length is 32 characters"
      }
    }
  }
})

4. Create a form

function Form() {
    // ...
    return (
      <form onSubmit={handleSubmit}>
        <input name="username" onChange={handleChange} />
        <p>{errors.username}</p>
        <button>Submit</button
      </form>
    )
}

5. Create handleSubmit function

const handleSubmit = ev => { 
    ev.preventDefault()
            
    const errorsExist = checkErrors()   
    if(errorsExist) return 
            
    console.log(data) 
    
    // manipulate data 
}

Check the React Native version here

Made by Marius Atasiei