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

reactjs-use-form

v1.5.0

Published

Reactive form management and input field validation hook

Downloads

113

Readme

useForm(📋, ⚙️) ⇒ Reactive Form ⚛️

build and tests code style: prettier GitHub code size in bytes npm minified bundle size npm gzipped bundle size typescript

Reactive form management and input field validation hook

Create a form model, flag input fields as required or add a value validation function with custom error messages. useForm will validate the inputs as the user types, when there are no errors the form gets enabled for submission. On form submission, it executes a callback function the user provides.

Requirements:
  • 📋 Form model with optional validation function.
  • ⚙️ Function to run after form validation and submission.
  • ⚛️ React functional component with a form.

Install

npm install reactjs-use-form

Usage

Steps:
  1. create a form model:
import { FormModelType } from 'reactjs-use-form';

export const formModel: FormModelType = {
  currentPassphrase: {
    value: '',
    required: true,
  },
  newPassphrase: {
    value: '',
    required: true,
    validator: (newPassphrase, values) => {
      if (newPassphrase === values?.currentPassphrase) {
        return 'New password must be different from current password';
      } else if (newPassphrase.length <= 5) {
        return 'Password must be at least 6 characters long';
      } else if (newPassphrase !== values?.verifyPassphrase) {
        return 'Passwords do not match';
      } else return '';
    },
  },
  verifyPassphrase: {
    value: '',
    required: true,
    validator: (verifyPassphrase, values) => {
      return verifyPassphrase !== values?.newPassphrase ? 'Passwords do not match' : '';
    },
  },
};
  1. prepare a submit callback function, for example: function handleSubmit() {...}.

  2. use the form model with the callback function in useForm hook in a functional react component:

import React from 'react';
import { useForm, ValuesType } from 'reactjs-use-form';
import { formModel } from './formModel';

const ChangePassphraseComponent = () => {
  const {
    values,
    errors,
    handleOnChange,
    handleOnSubmit,
    isDisabled,
    isSubmitted,
    isDirty
  } = useForm(formModel, handleSubmit);

  const { currentPassphrase, newPassphrase, verifyPassphrase }: ValuesType = values;

  function handleSubmit() {
    if (isDirty) formSubmitCallback();
  }

  return (
    <form onSubmit={handleOnSubmit}>
      <div>
        <label>Current Passphrase</label>
        <input
          type="password"
          name="currentPassphrase"
          value={currentPassphrase}
          onChange={handleOnChange}
        />
        <span>{errors.currentPassphrase.message}</span>
      </div>
      <div>
        <label>New Passphrase</label>
        <input
          type="password"
          name="newPassphrase"
          value={newPassphrase}
          onChange={handleOnChange}
        />
        <span>{errors.newPassphrase.message}</span>
      </div>
      <div>
        <label>Verify Passphrase</label>
        <input
          type="password"
          name="verifyPassphrase"
          value={verifyPassphrase}
          onChange={handleOnChange}
        />
        <span>{errors.verifyPassphrase.message}</span>
      </div>
      <span>{isSubmitted ? 'Passphrase has been changed!' : null}</span>
      <button type="submit" disabled={isDisabled}>
        <span>Submit</span>
      </button>
    </form>
  );
};
import React from 'react';
import { Button, FormControl, FormGroup, FormHelperText, FormLabel, TextField } from '@material-ui/core';
import { useForm, ValuesType } from 'reactjs-use-form';
import { formModel } from './formModel';

const ChangePassphraseComponent = () => {
  const {
    values,
    errors,
    handleOnChange,
    handleOnSubmit,
    isDisabled,
    isSubmitted,
    isDirty
  } = useForm(formModel, handleSubmit);

  const { currentPassphrase, newPassphrase, verifyPassphrase }: ValuesType = values;

  function handleSubmit() {
    if (isDirty) formSubmitCallback();
  }

  return (
    <form onSubmit={handleOnSubmit}>
      <FormGroup>
        <FormControl>
          <TextField
            required={true}
            label='Current Passphrase'
            type='password'
            name='currentPassphrase'
            error={errors.currentPassphrase.hasError}
            value={currentPassphrase}
            onChange={handleOnChange} />
          <FormHelperText error={errors.currentPassphrase.hasError}>
            {errors.currentPassphrase.message}
          </FormHelperText>
        </FormControl>
      </FormGroup>
      <FormGroup>
        <FormControl>
          <TextField
            required={true}
            label='New Passphrase'
            type='password'
            name='newPassphrase'
            error={errors.newPassphrase.hasError}
            value={newPassphrase}
            onChange={handleOnChange} />
          <FormHelperText error={errors.newPassphrase.hasError}>
            {errors.newPassphrase.message}
          </FormHelperText>
        </FormControl>
      </FormGroup>
      <FormGroup>
        <FormControl>
          <TextField
            required={true}
            label='Verify Passphrase'
            type='password'
            name='verifyPassphrase'
            error={errors.verifyPassphrase.hasError}
            value={verifyPassphrase}
            onChange={handleOnChange} />
          <FormHelperText error={errors.verifyPassphrase.hasError}>
            {errors.verifyPassphrase.message}
          </FormHelperText>
        </FormControl>
      </FormGroup>
      {isSubmitted ? <Alert variant='standard' severity='success' action='Passphrase has been changed!' /> : null}
      <Button type='submit' disabled={isDisabled}>
        Submit
      </Button>
    </form>
  );
};

Options

useForm takes two params: formModel and formSubmitCallback and returns the rest.

const {
  values,
  errors,
  handleOnChange,
  handleOnSubmit,
  isDisabled,
  isSubmitted,
  isDirty
} = useForm(formModel, formSubmitCallback);

| Param | Type | Description | | ------------------ | -------------------------------------------------------------- | --------------------------------------------------------- | | values | ValuesType | returns form values state object | | errors | ErrorsType | returns form errors state object | | handleOnChange | HandleOnChangeType | binds to a HTMLInputElement: change event | | handleOnSubmit | HandleOnSubmitType | binds to a HTMLFormElement: submit event | | isDisabled | boolean | returns true / false when the form is valid / invalid | | isSubmitted | boolean | returns true when the form was submitted without errors | | isDirty | boolean | returns true when the form recieves data | | formModel | FormModelType | initial form model with optional validation function | | formSubmitCallback | () => void | function to run after form validation and submission |

Type definitions: docs/definitions.md

License

GitHub