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

@xtreamsrl/react-forms

v0.2.0

Published

This package exposes a FormProvider and the following hooks: useForm, useFormContext, useController. It is useful to ease form management.

Downloads

327

Readme

@xtreamsrl/react-forms

This package exposes a FormProvider and the following hooks: useForm, useFormContext, useController. It is useful to ease form management.

Installation

npm install @xtreamsrl/react-forms

Usage

In order to use this library properly it is advantageous to follow the description of the single hooks. They are listed in an order that allows to add each required piece step by step.

useForm

First thing first, it is necessary to rely on the useForm hook to have access to methods and properties to manage and control forms. This hook is used to encapsulate the logic and state related to form management.

The useForm hook accepts an object containing two fields:

  1. initialValues to populate the entire form with default values.
  2. validationSchema to integrate yup inputs' validation.

! Caution: At the moment only yup is accepted as validator, despite react-hook-form supports Yup, Zod, Joi, Vest, Ajv and many others.

import {useForm} from "@xtreamsrl/react-forms"
import * as yup from "yup"

const validationSchema = yup.object().shape({
  email: yup.string().email().required("Required"),
  password: yup.string().min(5, "Password is too short").required("Required"),
});

See yup on GitHub to know more about validation.

const form = useForm<LoginData>({initialValues: {email: "", password: ""}, validationSchema});

The useForm return value has three fields:

  • formProps contains methods to handle the form. The following two fields are subfields of this object.
  • formState is an object that contains information about the entire form state. It helps to keep on track with the user's interaction with the form application.
  • reset allows to reset the entire form state, fields reference, and subscriptions. It also allows partial reset through optional parameters.

FormProvider

Once form management methods are available, it is possible to define a form that will be wrapped using a provider.

When wrapping the form, it can be helpful to specify the object type to be handled. In other terms, it can be specified the TypeScript type of the fields that make up the entire form. For example, LoginData has been defined from the validation schema: type LoginData = yup.InferType<typeof validationSchema> and specified to the Provider.

Then, it requires formProps, containing all the methods returned by the useForm hook.

import {FormProvider} from "@xtreamsrl/react-forms"
<FormProvider<LoginData> {...form.formProps}>
      <form onSubmit={form.formProps.handleSubmit((values, event) => {
        event?.preventDefault();
        login(values.email, values.password)
      })}>
        <Input name="email" type="email" placeholder="email"/>
        <Input name="password" type="password" placeholder="password"/>
        <Button type="submit">Login</Button>
      </form>
    </FormProvider>

See the useController blow to see an example of how to define the Input component visible in this snippet.

useController

This hook is used to bind a single input field to the form, it powers the Controller. It provides a way to manually control an input field while still integrating with the overall form state. The Controller component is a wrapper around the input component that works with the useController hook.

The hook accepts an object containing:

  • name: unique name of the input, it is the only required field.
  • control: control object provided by invoking useForm. Optional when using FormProvider.
  • rules.
  • shouldUnregister: value that indicate that the Input will be unregistered after unmount and defaultValues will be removed as well.
  • defaultValue: it cannot be undefined.
import {useController} from "@xtreamsrl/react-forms"

export function Input({name, type, placeholder}: {
  name: string, type: string, placeholder: string
}) {
  const {
    field: {
      ref,
      value,
      ...inputProps
    },
    fieldState: {
      error,
      invalid
    }
  } = useController({name});

  return 
  <div>
    <input placeholder={placeholder} type={type} {...inputProps}/>
    <span> {error?.message?.toString()} </span>
  </div>
}

The useController return values (field, fieldState and formState) can be explored in the dedicated page of the react-hook-form documentation, given that this hook return values have not been manipulated before being returned.

useFormContext

This custom hook allows to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. It returns setError, watch, formState. Remember that it is necessary to wrap the form with the FormProvider component for useFormContext to work properly.

import { useForm, FormProvider, useFormContext } from "@xtreamsrl/react-forms"

export default function App() {
  const {formProps: methods} = useForm()
  const onSubmit = (data) => console.log(data)

  return (
    <FormProvider {...methods}>
      // pass all methods into the context
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        {/*...*/}
        <NestedInput />
        <input type="submit" />
      </form>
    </FormProvider>
  )
}

function NestedInput({name: string}) {
  const {setError, watch, formState} = useFormContext()
  
  const value = watch(name);
  const companyName = watch('companyName');
  const companyAddress = watch('companyAddress');

  const invalid = name in formState.errors;
  
  // ...
}

The watch method watches specified inputs and return their values. It is useful to render input value and for determining what to render by condition. See more on the documentation page.

The setError function allows you to manually set one or more errors. See more about setError.

Who we are