1.0.0 • Published 3 years ago

react-native-better-hook-form v1.0.0

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

React Native Better Hook Form

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

How to install

npm install react-native-better-hook-form

OR

yarn add react-native-better-hook-form

How to use

1. Import the hook:

import { useForm } from "react-native-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 (
      <View>
        <TextInput name="username" onChange={(value) => handleChange("username", value)} />
        <Text>{errors.username}</Text>
        <Button title="submit" onPress={handleSubmit} />
      </View>
    )
}

5. Create handleSubmit function

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

Check the React version here

Made by Marius Atasiei