1.9.12 • Published 4 years ago

@mlaopane/formhook v1.9.12

Weekly downloads
57
License
MIT
Repository
gitlab
Last release
4 years ago

FormHook

pipeline status coverage report

Installation

yarn add @mlaopane/formhook

OR

npm i --save @mlaopane/formhook

Checkout the examples for usage.

What is FormHook

FormHook is a library allowing developers to easily create and handle forms with React.

Why should I use FormHook

Maintaining a form state is cumbersome.

Traditionally you need to :

  • Update the state when an input changes
  • Process validation based on events (change, blur, submit)

FormHook will handle these tasks for you.

How it works

The library exposes a few components and functions to help you create cleaner forms.

Under the hood, it uses :

By using the <Form>...</Form> component, a context is internally created and maintained.

Any child inside the Form will have access to the context.

Examples

Here is a simple example :

// LoginForm.jsx

import React from 'react';
import { Form, Input, Button } from '@mlaopane/formhook';
// Your custom validator (defined below)
import emailValidator from './emailValidator';

export default function SignInForm() {
    const initialValues = {
        email: '',
        password: '',
    };

    const handleSubmit = ({ form, dispatch }) => {
        /**
         * Do whatever you need with the values
         * like sending them to an API
         */
        console.log(form.values);

        /**
         * Set form.isSubmitting to `false`
         * The provided Button component is automatically disabled
         * when the form is being submitted
         */
        dispatch({ type: 'END_SUBMIT' });
    };

    // The state of the form is handled by the Form component
    return (
        <Form initialValues={initialValues} onSubmit={handleSubmit}>
            <Input name='email' validate={emailValidator.validate} />
            <Input name='password' />
            <Button>Sign in</Button>
        </Form>
    );
}
// emailValidator.js

/**
 * You need to return an empty string if there is no error
 */
export const validate = async ({ field }) => {
    if (!field.value) {
        return 'E-mail is mandatory';
    }
    if (!field.value.includes('@')) {
        return 'Invalid e-mail';
    }
    return '';
};

If you need a more advanced example, you can checkout the examples directory of the formhook's repository.

FormHook API

The public components/functions can be retrieved from the global module like this :

// Example
import { Form, FormContext, useInput } from '@mlaopane/formhook';

Main components

Form

The Form component is mandatory to leverage the power of this library. Pass in the initialValues and the onSubmit function handler.

Input

The Input component automatically dispatches new values on every change.
Just pass in the name as a prop.

It allows validation too by passing async functions (cf. Validation).

To define a validation function, you can declare an async function (cf. async/await).
This function must return an error string or an empty string if there is no error.

Spy

You may need to retrieve the form state to use it outside of the form. You could implement your own component using the exposed FormContext or more simple, use the provided Spy.

import React from 'react';
import { Form, Spy } from '@mlaopane/formhook';

export default function MyComponent() {
    const initialValues = { fieldName: '' };

    function showMeWhatYouGot({ form }) {
        console.log(form);
    }

    return (
        <Form initialValues={initialValues}>
            <Spy hookContext={showMeWhatYouGot} />
        </Form>
    );
}

FormContext

The FormContext can be imported and used by any child component of the Form.

It exposes an tuple with the form state and the dispatch function.

import React from 'react';
import { FormContext } from '@mlaopane/formhook';

export default function MyComponent() {
    const [form, dispatch] = React.useContext(FormContext);
    // ...
    return <div>{JSON.stringify(form)}</div>;
}

The form state looks like this :

{
    "errors": {
        "fieldName": ""
    },
    "focused": "",
    "isValid": true,
    "isSubmitting": false,
    "options": {
        "fieldName": []
    },
    "touched": {
        "fieldName": false
    },
    "validators": {
        "fieldName": {}
    },
    "values": {
        "fieldName": ""
    }
}

Validation

The field components accept validation functions as props :

  • validateOnChange is called when the input value changes.

  • validateOnBlur is called when the input loses the focus.

  • validateOnSubmit is called on form submission.

  • validate serves as a fallback.

In summary : If you don't need custom validation function for every event, just use validate.

1.9.12

4 years ago

1.9.11

4 years ago

1.9.10

4 years ago

1.9.8

5 years ago

1.9.7

5 years ago

1.9.6

5 years ago

1.9.5

5 years ago

1.9.4

5 years ago

1.9.3

5 years ago

1.9.2

5 years ago

1.9.1

5 years ago

1.9.0

5 years ago

1.8.0

5 years ago

1.7.0

5 years ago

1.6.0

5 years ago

1.5.0

5 years ago

1.4.4

5 years ago

1.4.3

5 years ago

1.4.1

5 years ago

1.4.0

5 years ago

1.3.4

5 years ago

1.3.2

5 years ago

1.3.1

5 years ago

1.3.0

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago

0.1.24

5 years ago

0.1.23

5 years ago

0.1.22

5 years ago

0.1.20

5 years ago

0.1.19

5 years ago

0.1.18

5 years ago

0.1.17

5 years ago

0.1.16

5 years ago

0.1.15

5 years ago

0.1.14

5 years ago

0.1.13

5 years ago

0.1.12

5 years ago

0.1.11

5 years ago

0.1.10

5 years ago

0.1.9

5 years ago

0.1.8

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago