usetheform
Edit page
Introduction
Components
CollectionFormPropsBasic usageReducersValidation - SyncValidation - AsyncFormContextInputPersistStateOnUnmountSelectTextArea
Hooks
Material UI - React Select

Form

The Form is the most important component in usetheform. It renders all the Fields and keeps the entire form state synchronized.

Props

onInit: function

  • A function invoked when the Form is initialized.
const onInit = (formState, isFormValid) => { // some operation }

onChange: function

  • A function invoked when any Form Field changes its value.
const onChange = (formState, isFormValid) => { // some operation }

onReset: function

  • A function invoked when the form has been reset to its initial state.
const onReset = (formState, isFormValid) => { // some operation }

onSubmit: function

  • A function invoked when the submit button has been pressed.
  • The function may return either a Promise or a boolean value of true/false.
const onSubmit = (formState) => { // some operation };
const onSubmit = (formState) => new Promise((resolve, reject) => { // some async operation });
  • Cases:
    • If the function returns a Promise which is resolved, it will increment the value named submitted.
    • If the function returns a boolean value true or no return at all, it will increment the value named submitted.
    • If the function returns a Promise which is rejected, the value named submitted will not be incremented.
    • If the function returns a boolean value false, the value named submitted will not be incremented.
const { submitted, submitAttempts } = useForm();
  • It will be only invoked if the form passes all the validations added at any level (Collections or Fields).
  • For each invocation, the value submitAttempts will be incremented.

initialState: object

  • It is a plain object that represents the initial state of the form.

reducers: array | function

(nextState, prevState) => nextState
  • An array whose values correspond to different reducing functions.
  • Reducer functions specify how the Form's state changes.

touched: boolean

  • Default value of false.

  • If true, sync validation messages will be shown only when the event onBlur of any forms's field is triggered by the user action at any level of nesting.

action: string

  • The action attribute specifies where to send the form-data when a form is submitted.

  • Possible values:

    • An absolute URL - points to another web site (like action="http://www.example.com/example.html")
    • A relative URL - points to a file within a web site (like action="example.html")

innerRef: object (a mutable ref object)

  • When you need to access the underlying DOM node created by Form (e.g. to call focus), you can use a ref to store a reference to the form dom node.
const ref = useRef(null)
<Form innerRef={ref} name="form">...fields...</Form>

Basic usage

Example 1

A simple form with the initial state passed as Form prop.

import { Form, Input } from 'usetheform'
  • {} 0 keys

    Example 2

    A simple form with the initial state passed straight to the Form's Field.

    import { Form, Input } from 'usetheform'
    • {} 0 keys

      Reducers

      import { Form, Collection } from 'usetheform';
      import { Item } from './components/Item';
      import { reduceTotalPrice,reduceTotalQuantity } from './components/Item/utils';
      • {} 0 keys

        Detailed Explanation:

        export const Item = ({ price, qty, desc }) => {
        return (
        <Collection object>
        <Input type="number" name="price" placeholder="Price" min={1} value={price} />
        <Input type="number" name="qty" placeholder="Quantity" min={1} value={qty} />
        <Input type="text" name="description" placeholder="Description" value={desc} />
        </Collection>
        );
        }
        export const reduceTotalPrice = formState => {
        const { items = [] } = formState;
        const totalPrice = items.reduce((total, { price = 0, qty = 0 }) => {
        total += price * qty;
        return total;
        }, 0);
        return { ...formState, totalPrice };
        };
        export const reduceTotalQuantity = (formState) => {
        const { items = [] } = formState;
        const totalQuantity = items.reduce((total, { qty = 0 }) => {
        total += qty;
        return total;
        }, 0);
        return { ...formState, totalQuantity };
        };

        Validation - Sync

        Validation at Form level:

        • touched=false: error messages will be shown on Form initialization and when any Field is edited.
        • touched=true: error messages will be shown when any Field at any level of nesting is touched/visited.
        import { Form, Input, Collection, useValidation } from 'usetheform'
        • {} 0 keys

          Validation - Async

          Async Validation for Form is triggered on Submit event. The form submission is prevented if the validation fails. It means that the onSubmit function passed as prop to the Form component will not be invoked.

          import { Form, Collection, Input, useAsyncValidation } from 'usetheform';
          • {} 0 keys

            Detailed Explanation:

            import { useForm } from 'usetheform'
            const Submit = () => {
            const { isValid } = useForm();
            return (
            <button disabled={!isValid} type="submit">
            Submit
            </button>
            );
            };
            export const asyncTestForm = ({ values }) =>
            new Promise((resolve, reject) => {
            // it could be an API call or any async operation
            setTimeout(() => {
            if (!values || !values.a || !values.b) {
            reject("Emtpy values are not allowed ");
            }
            if (values.a + values.b >= 5) {
            reject("The sum must be less than '5'");
            } else {
            resolve("Success");
            }
            }, 1000);
            });