Simple declarative React form handling hook which renders the page as much times as you expect.

栏目: IT技术 · 发布时间: 4年前

内容简介:React hook for gathering and validating form data without unnecessary re-renders.The idea is that form state stored inNotice, that you have to describe

useReactiveForm

React hook for gathering and validating form data without unnecessary re-renders.

Install:

npm install use-reactive-form
yarn add use-reactive-form

Usage:

The idea is that form state stored in useRef . When it changes, it does not re-render the component. Ways to re-render form:

  1. Call validate() function.
  2. Use validateOnChange: true which is basically the same as #1. If after validation message of the error has not changed, the component will not re-render.
  3. Call update() function.

Step 1: Describe initial values and interface.

interface IFormData = {
    user: string;
    books: {
        title: string;
        author: string;
    }[]
}

const initial: IFormData = {
    user: '',
    books: [
      {
        title: '',
        author: '',  
      }
    ],
}

Step 2: [Optional] Describe validation schema in Yup syntax.

import { array, object, string } from 'yup';

// ...

const validation = object().shape({
    user: string().required('This field is required')
                  .max(20, 'Character limit exceeded'),
    books: array().of(object().shape({
      title: string().required('This field is required'),
      author: string().required('This field is required'),
    })),
});

Step 3: Create config.

import { IUseReactiveForm } from 'use-reactive-form';

// ...

const config: IUseReactiveForm<IFormData> = {
    fields: initial,
    schema: validation,
    validateOnChange: true
  };

Config keys:

fields: T - Form fields / structure  
deps?: boolean[] - Array of boolean dependencies that trigger re-render 
schema?: any - Validation schema  
separator?: string - Separator for name property of inputs. _ is set by default  
validateOnChange?: boolean - Validate on input change
actionOnChange?: (values: T) => void - Fire function on input change
updateTriggers? string[] - array of name attributes whose change triggers re-render

Step 4: Use Hook

const { values, ref, update, validate, clear } = useReactiveForm<IFormData>(config);

/**
values - get current form state
ref - reference to <form> tag
validate() - function which validates the form
errors - gets errors after validation 
clear() - function which form values form and errors
update() - function which re-renders form. It is needed in case when you dynamically add fields.
**/

Step 5: Connect hook to the form.

const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (validate()) {
      console.log(values);
    } else {
      console.log(errors);
    }
  };

return (
  <form ref={ref} onSubmit={onSubmit}>
  
    <div>
      <input type='text' name={'user'} defaultValue={values.name}/>
      { errors.user.error && <p> {errors.user.error} </p> }
    </div>
  
    {
    values.books.map((b, i: number) => (
        <div key={`book${i}`}>
            <input type='text' name={`books_${i}_title`}/>
            <input type='text' name={`books_${i}_author`}/>    
        </div>
      ))
    }
  
    <button type='submit' onClick={onSubmit}> Submit </button>
  
  </form>
)

Notice, that you have to describe name attribute as a path to the key in your form object. Instead of common separators ( . , [] ) use _ or your separator described in config .

To get error message use errors . It is an object with the same structure as your form object, but instead of just values, it contains object { value: string, error: string } . Therefore, error message for user field located in errors.user.error .

Any action triggered on the <input/> will provide it with one of the following classes: touched , dirty or invalid .

Dynamic fields.

If you want to add some fields dynamically, you need to use update() function. Let's say you want to add a new book. You will need to copy values and push a new book object to the values.books array.

const addBook = () => {
    update({
      ...values,
      books: [...values.books, {
        title: '',
        author: ''
      }]
    });
  };
  
<button type='button' onClick={addBook}> Add book </button>

Action on input change.

actionOnChange is a parameter, which you may want to set to true when you have to fire a function when any of the inputs value changes. It may be desirable when you submit form dynamically.


以上所述就是小编给大家介绍的《Simple declarative React form handling hook which renders the page as much times as you expect.》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

探索需求

探索需求

章柏幸、王媛媛、谢攀、杰拉尔德・温伯格、唐纳德・高斯 / 章柏幸、王媛媛、谢攀 / 清华大学出版社 / 2004-7-1 / 39.00元

本书将与您一起寻找"什么是客户真正想要的"这一问题的答案。 本书着眼于系统设计之前的需求过程,它是整个开发过程(如何设计人们想要的产品和系统)中最有挑战性的那部分。通过对一些需求分析中的常见误区和问题的分析和讨论,从和客户沟通开始,深入研究一些可能的需求,澄清用户和开发者期望值,最终给出了能够大幅度提高项目成功几率的一些建议方法。 本书由该领域内公认的两位作者合著,搜集了他们在大大小小......一起来看看 《探索需求》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换