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

rhf-conditional-logic

v0.1.2

Published

Conditional Logic for React Hook Forms. Fully typed and compatible with resolvers (e.g. Zod)

Downloads

1,455

Readme

Conditional Logic for React Hook Forms

A tiny library that makes it easy to define conditional logic in one place, expose it in components for conditional rendering, and prune hidden field values before validation & submission.

FeaturesGetting StartedChangelog

npm minzip types

Features

  • Define conditional logic (whether to show/hide fields) in a single typed object:

    const conditions = {
      // Show "Other Caterer" field if "Other" option is selected
      otherCaterer: getValues => getValues('caterer') === 'Other',
    } satisfies FieldConditions<FormSchema>;
  • Use useConditionalForm() (a drop-in replacement for useForm()) to prune hidden field values before validation:

    const { register } = useConditionalForm<FormSchema>({
      conditions,
      resolver: zodResolver(formSchema),
      defaultValues: {...},
    });

    This way you can track hidden field values with shouldUnregister = false but don't have to worry about them showing up in errors and preventing submission, or even worse, being submitted when the user didn't intend to submit them!

  • Use useCondition() (similar to useWatch()) to check if one or more conditional fields should be visible.

    const [showOtherOption] = useCondition(['otherCaterer'], conditions, getValues, control);
  • Fully typed with Typescript! Get autocompletion & validation based on your Zod schema (or whatever validator you're using)

  • You can even define conditional logic for every item in an array (e.g. rendered via useFieldArray) with # wildcard that stands in for "current index":

    const conditions = {
      // Show wine pairing options for each guest over 21
      ['guests.#.wine']: getValues => getValues('guests.#.age') >= 21,
    };

Getting Started

npm i rhf-conditional-logic

Totally up to you, but I find it cleaner to stick schemas in one file and components in another, e.g.

// form-schema.ts
import { z } from 'zod';
import { FieldConditions } from 'rhf-conditional-logic';

// Define form schema with conditional fields optional, since hidden field values
// will not be included in the form submission
export const formSchema = z.object({
  caterer: z.enum(['Elephants Catering', 'Delta BBQ', 'Other']),
  otherCaterer: z.string().min(2).optional(), // Shown if "caterer" is "Other"
  guests: z.array(
    z.object({
      age: z.number(),
      wine: z.enum(['Red', 'White', 'Rosé on ice', 'None']).optional(), // Show if 21+
    })
  ),
});
export type FormSchema = z.infer<typeof formSchema>;

// All conditional logic goes in a single declarative object
// { path.to.field: (getValues) => boolean }
export const conditions = {
  // Show "Other Caterer" if "Other" option is selected
  otherCaterer: getValues => getValues('caterer') === 'Other',
  // Show "Wine" options for guests over 21
  // Note: "#" wildcard stands-in for "current" array index
  ['guests.#.wine']: getValues => getValues('guests.#.age') >= 21,
} satisfies FieldConditions<FormSchema>;
// Form.tsx
import { zodResolver } from '@hookform/resolvers/zod';
import { useConditionalForm, useCondition } from 'rhf-conditional-logic';
import { FormSchema, conditions, formSchema } from './form-schema';

export function Form() {
  // useConditionalForm() wraps useForm() and prunes hidden field values
  // before validation / submission
  const { getValues, control } = useConditionalForm<FormSchema>({
    conditions, // Your conditional logic definition goes here
    resolver: zodResolver(formSchema), // Required
    defaultValues, // Required
  });

  // "showCaterer" boolean will update based on "caterer" value
  const [showCaterer] = useCondition(['otherCaterer'], conditions, getValues, control);

  const { fields: guestFields, append: appendGuest } = useFieldArray({
    control,
    name: 'guests',
  });

  const onSubmit = (validVisibleFields: FormSchema) => {
    // Do something with pruned & validated form submission!
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* ... form fields go here */}
      {guestFields.map((field, i) => (
        <Guest key={field.id} index={i} />
      ))}
    </form>
  );
}

function Guest({ index }: { index: number }) {
  const { register, getValues, control } = useFormContext<FormSchema>();

  // "showWineField" boolean will update based on "age" value
  // for this particular field array index
  const [showWineField] = useCondition(
    [`guests.${index}.wine`],
    conditions,
    getValues,
    control
  );

  return <fieldset>...</fieldset>;
}

Curious about the backstory of this library? Check out my article on Type-Safe Conditional Logic in React Hook Forms + Zod.

Future improvements

  • Update useCondition() signature to allow for single field (instead of array).
  • Update useCondition() to use useFormContext() and allow for optionally passing fewer parameters to it.