npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mlaopane/formhook

v1.9.12

Published

Handle forms in React using hooks

Downloads

17

Readme

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.