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

use-managed-form

v1.2.0

Published

A React custom hook for effortless controlled form management, providing built-in state handling and validations for interactive and responsive forms.

Downloads

24

Readme

useControlledForm

Easily manage your React forms with useControlledForm, a custom hook that simplifies state management and validation for interactive and responsive forms.

Installation

npm install use-managed-form

Usage

First, import the hook from the package:

import useControlledForm from 'use-managed-form';

Basic Form Setup

Declare your form initial state:

const initialFormState = {
  email: '',
  password: '',
};

Now you can use the initialFormState object to initialize your form with default values:

useControlledForm(initialFormState);

Understanding the Returned Object

The useControlledForm hook returns an object with the following properties:

  • [inputKey]: the value of the input field with the corresponding key in the initial state object.
  • form: an object with the following properties:
    • [inputKey]:
      • id: the input key.
      • value: the current value of the input.
      • error: the current validation error associated with the input.
    • reset: a function that resets all form fields to their initial values and clears all validation errors.
    • clearErrors: a function that clears all validation errors without resetting the field values.
    • hasErrors: a function that returns a boolean value indicating whether there are any validation errors.
  • onInputChange: a function that updates the value of a form field when the user interacts with it.
  • attachInputError: a function that associates an error message with a specific form field.

You can extract all this properties directly from the returned object, or use destructuring to extract them individually. Here's an example:

const { form, onInputChange, attachInputError } = useControlledForm(initialFormState);

You could also extract each input value:

const { email, password, onInputChange } = useControlledForm(initialFormState);

Simple JSX Implementation

A simple JSX implementation of the previous form would look like this:

<form>
  <div>
    <label htmlFor='email'>Email</label>
    <input type='email' name='email' value={email} onChange={onInputChange}/>
  </div>
  <div>
    <label htmlFor='password'>Password</label>
    <input type='password' name='password' value={password} onChange={onInputChange} />
  </div>
  <button type='submit'>Submit</button>
</form>

Note: Ensure that the name attribute of each input matches the corresponding key in the initial state object passed to useControlledForm.

Recommended JSX Implementation

However, the recommended way is to extract each input value from the form object, the reason is that you can also access the input error message from it, here's an example using the form object:

const { form, onInputChange } = useControlledForm(initialFormState);

// ...

<form>
  <div>
    <label htmlFor='email'>Email</label>
    <input type='email' name='email' value={form.email.value} onChange={onInputChange}/>
    <p>{form.email.error}</p>
  </div>
  <div>
    <label htmlFor='password'>Password</label>
    <input type='password' name='password' value={form.password.value} onChange={onInputChange} />
    <p>{form.password.error}</p>
  </div>
  <button type='submit'>Submit</button>
</form>

Attaching Validation Errors

You could attach validation errors to inputs using the attachInputError method:

const { form, onInputChange, attachInputError } = useControlledForm(initialFormState);

// ...

const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();
  if (form.email.value === '') attachInputError(form.email.id, 'Email is required');
  if (form.password.value === '') attachInputError(form.password.id, 'Password is required');
  if (form.hasErrors()) return;
  // Submit form
};

The validation errors attached to each input are accessible from the form object:

form.[inputKey].error

Handling Boolean Values

For boolean values such as checkboxes, use the checked attribute:

const { form, onInputChange } = useControlledForm({
  rememberMe: false,
});

// ...

<input type='checkbox' name='rememberMe' onChange={onInputChange} checked={form.rememberMe.value} />

Resetting the Form

Reset all form fields to their initial values and clear errors using the reset method of the form object:

<button type='button' onClick={form.reset}>Reset</button>

To clear all validation errors without resetting the field values, use the clearErrors method:

form.clearErrors();

Contributing

The source code of this package is available on GitHub. Contributions are welcome.

This package is also published on npm.