1.1.0 • Published 4 years ago

react-hooks-dynamic-form v1.1.0

Weekly downloads
9
License
ISC
Repository
github
Last release
4 years ago

React hooks dynamic form library

Downloads Milestones Latest tag License Peer React

A simple but powerful library for managing form states, either by using the custom React hooks API for managing your own form, or using the library's auto generated Form Component (work in progress).

See the full documentation and examples from our storybook

Getting Started

npm install --save react-hooks-dynamic-form

Usage

1. User defined parameters

As introducted above, the library provide 2 ways for managing form states. Both ways start by setting the form parameters:

1.1. Field definitions

An array containing fields definitions.

const FORM_FIELDS = [
  {
    type: "email",
    name: "email",
  },
  {
    type: "phone",
    name: "phone",
    isRequired: true,
    validateOnChange: true,
    errorMessages: {
      isRequired: "I NEED THIS PHONE NUMBER !",
      phone: "I WANT A BETTER NUMBER !",
    },
  },
  {
    type: "number",
    name: "age",
    isRequired: true,
    customValidators: [
      {
        validate: (value, formData) => !Number.isNaN(value) && value >= 18,
        errorMessage: "You must be over 18 !",
      },
    ],
  },
];

Please note, some properties are only for library's Form Component, such as className, label, render ... In case of using API on user's own custom form, only logical properties for managing state are taken into account. See list below.

--- Common settings for Form API and Form Component

PropertyTypeDescriptionDefault
namestringHTML name attribute, also used as field identifier in the form, must be unique
typestringField type that will be use for adding default validation rule and render method when using Form component. See FieldTypeEnum for available option"text"
valueanyInitial field value
isRequiredboolean | functionIf true, the field is required for validation. Can be a predicate with formData as parameter in case of conditional validation based on other fieldfalse
customValidatorsArrayArray of custom validation rules { validate: (value, formData) => boolean, errorMessage: string }[]
errorMessagesObjectValidation error messages. Please note, "email" and "phone" are only applicable to related type{ isRequired: "This field is required", email: "Invalid email", phone: "Invalid phone number", default: "Invalid field value"}
validateOnChangebooleanIf true, validate field on changefalse
disableBuiltInValidatorbooleanIf true, disable built-in validator, applicable to type with default validator (email, phone)false

--- Settings only applicable to Form Component

PropertyTypeDescriptionDefault
WorkInProgress ...💯👍

1.2. Default settings for all fields

We can provide a default common settings for all fields.

Please note, these settings will be merged and eventually overridden by each specific field definition above.

const DEFAULT_SETTINGS = {
  validateOnChange: true,
  errorMessages: {
    isRequired: "A custom message for required field",
    default: "A custom message for incorrect input",
  },
};

1.3. Remote values

Sometimes the fields values can't be defined on initialization but rather dynamically from external sources (such as server-side or parent components ...). In this case we can pass an object containing key : value combos and the library will watch for values change and take care of updating the form accordingly.

const remoteValues = { login: "Jane", phone: "01-02-03-04-05" };

These remote values will override all values from field definitions or default settings.

2. Using React Hooks API for managing your own form

You can use the library form API for managing your own form. Form API provide these properties:

interface FormApi {
  /**
   * indicating whether form data is initialized
   */
  isInit: boolean;
  /**
   * current field values { key: value }
   */
  values: FormValues;
  /**
   * update form field value
   */
  setFieldValue: (name: string, value: FieldValueType) => void;
  /**
   * validate a field
   */
  validateField: (name: string) => void;
  /**
   * validate all form fields
   */
  validateForm: () => boolean;
  /**
   * return field input error if there is any
   */
  getFieldInputError: (fieldName: string) => string | null;
  /**
   * reset form to initial settings
   */
  resetForm: () => void;
}

Form API can be used as custom React hooks:

import { useFormApi } from "react-hooks-dynamic-form";

const CustomForm = ({ remoteData }) => {
  const { isInit, values, setFieldValue, validateField, getFieldInputError } = useFormApi(
    FORM_FIELDS,
    DEFAULT_SETTINGS,
    remoteData
  );
  return isInit ? (
    <div className="my-form">
      <div className="field">
        <label>Login that valid itself on change: </label>
        <input
          name="login"
          className={getFieldInputError("login") ? "field--error" : ""}
          type="text"
          value={values.login as string}
          onChange={(ev): void => {
            setFieldValue("login", ev.target.value);
          }}
        />
        <span className="field-error-helper">{getFieldInputError("login")}</span>
      </div>
      <div className="field">
        <label>Phone that valid itself on blur: </label>
        <input
          name="phone"
          className={getFieldInputError("phone") ? "field--error" : ""}
          type="text"
          value={values.phone as string}
          onChange={(ev): void => {
            setFieldValue("phone", ev.target.value);
          }}
          onBlur={(): void => {
            validateField("phone");
          }}
        />
        <span className="field-error-helper">{getFieldInputError("phone")}</span>
      </div>
    </div>
  ) : null;
};

Please note, remoteValues are subject for useEffect immutable dependencies. These values MUST NOT be assigned inline with useFormApi call in order to avoid infinity loop overload. See example below.

Considering this example with inline initialization of remoteValues:

import { useFormApi } from "react-hooks-dynamic-form";

const CustomForm = () => {
  const { values, setFieldValue } = useFormApi(FORM_FIELDS, DEFAULT_SETTINGS, {
    fieldA: "value A",
    fieldB: "value B",
  });
  return <form>Anything...</form>;
};

Each component update can cause an infinity loop as a new remoteValues object is created. Therefore, only assign remoteValues in other scope (parent component, react hooks useState, useMemo ...). Anyway, for the purpose of remoteValues, it will never be initialized inline this way but only by error.

3. Using the library's auto generated Form component

Following the next major release, the library will provide an auto generated Form component that also take care of the form rendering according to field settings.

WORK IN PROGRESS ...
1.1.0

4 years ago

1.1.0-rc.2

4 years ago

1.1.0-rc.1

4 years ago

1.1.0-beta.2

4 years ago

1.1.0-rc.0

4 years ago

1.1.0-beta.1

4 years ago

1.1.0-beta.0

4 years ago

1.0.0-rc.7

4 years ago

1.0.0-rc.6

4 years ago

1.0.0-rc.5

4 years ago

1.0.0-rc.4

4 years ago

1.0.0-rc.3

4 years ago

1.0.0-rc.2

4 years ago

1.0.0-rc.1

4 years ago

0.1.0-beta.2

4 years ago

0.1.0-rc.1

4 years ago

0.1.0-rc.2

4 years ago

0.1.0-rc.0

4 years ago

1.0.0-rc.0

4 years ago

0.1.0-beta.1

4 years ago

0.1.0-beta

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago