Skip to content

Pyyfantic-sa/react-ts-form

 
 

Repository files navigation

banner

Build maintainable, typesafe forms faster 🏃💨

@ts-react/form handles the boilerplate involved when building forms using zod and react-hook-form without sacrificing customizability.

Features

  • 🥹 Automatically generate typesafe forms with zod schemas
  • 📎 Eliminate repetitive jsx and zod/rhf boilerplate
  • 🎮 Full control of components via typesafe props
  • 🤯 Headless UI that can render any react component
  • ❤️ Quality Of Life / Productivity features not feasible in vanilla zod and react-hook-form
  • 🤌🏻 Very tiny utility library (~3kb gzipped)
  • 👀 100% test coverage

API Docs

Quick Start

Installation

Make sure you have "strict": true in your tsconfig.json compilerOptions and make sure you set your editors typescript version to v4.9 (or intellisense won't be as reliable).

Install package and dependencies with your preferred package manager:

yarn add @ts-react/form

# required peer dependencies
yarn add zod react-hook-form @hookform/resolvers

Usage

Create a zod-to-component mapping to map zod schemas to your components then create your form with createTsForm (typically once per project):

// create the mapping
const mapping = [
  [z.string(), TextField],
  [z.boolean(), CheckBoxField],
  [z.enum(["placeholder"]), DropDownSelect],
] as const; // 👈 `as const` is necessary

// A typesafe React component
const MyForm = createTsForm(mapping);

Now just create form schemas with zod and pass them to your form:

const SignUpSchema = z.object({
  email: z.string().email("Enter a real email please."), // renders TextField
  password: z.string(),
  address: z.string(),
  favoriteColor: z.enum(["blue", "red", "purple"]), // renders DropDownSelect and passed the enum values
  isOver18: z.boolean(), // renders CheckBoxField
});

function MyPage() {
  function onSubmit(data: z.infer<typeof SignUpSchema>) {
    // gets typesafe data when form is submitted
  }

  return (
    <MyForm
      schema={SignUpSchema}
      onSubmit={onSubmit}
      renderAfter={() => <button type="submit">Submit</button>}
      // optional typesafe props forwarded to your components
      props={{
        email: {
          className: "mt-2",
        },
      }}
    />
  );
}

That's it! Adding a new field to your form just means adding an additional property to the schema.

It's recommended but not required that you create a custom form component to handle repetitive stuff (like rendering the submit button).

Creating Input Components

Form components can be any react component. The useTsController() hook allows you to build your components with the form state:

function TextField() {
  const { field, error } = useTsController<string>();
  return (
    <>
      <input
        value={field.value}
        onChange={(e) => {
          field.onChange(e.target.value);
        }}
      />
      {error?.errorMessage && <span>{error?.errorMessage}</span>}
    </>
  );
}

@ts-react/form will magically connecting your component to the appropriate field with this hook. You can also receive the control and name as props, if you prefer:

function TextField({ control, name }: { control: Control<any>; name: string }) {
  const { field, fieldState } = useController({ name, control });
  //...
}

This approach is less typesafe than useTsController.

If you want the control, name, or other @ts-react/form data to be passed to props with a different name check out prop forwarding.

Docs

  1. Quick Start
  2. Creating Input Components
  3. TypeSafe Props
  4. Dealing With Collisions
  5. Handling Optionals
  6. Error Handling
  7. Accessing useForm State
  8. Complex Field Types
  9. Rendering Non Input Components
  10. Customizing Form Components
  11. Default Values
  12. Prop Forwarding
  13. Manual Form Submission
  14. React Native Usage
  15. ❤️ Quality of Life / Productivity ❤️

TypeSafe Props

Based on your component mapping, @ts-react/form knows which field should receive which props:

const mapping = [
  [z.string(), TextField] as const,
  [z.boolean(), CheckBoxField] as const,
] as const;

//...
const Schema = z.object({
  name: z.string(),
  password: z.string(),
  over18: z.boolean(),
})
//...
<MyForm
  props={{
    name: {
      // TextField props
    },
    over18: {
      // CheckBoxField props
    }
  }}
/>

@ts-react/form is also aware of which props are required, so it will make sure you always pass required props to your components:

Here we get an error because <Component/> requires the prop required, and we didn't pass it.

return (
  <Form
    schema={FormSchema}
    onSubmit={() => {}}
    props={{
      field: {
        required: "Fixed!",
      },
    }}
  />
);

Fixed! We get all the same typesafety of writing out the full jsx.

Error Handling

You can handle errors with the fieldState returned from useTsController just like in react-hook-form, but @ts-react/form also returns an errors object that's more accurately typed than react-hook-forms's that should be used any time you are using an object schema to render one of your fields.

const { error } = useTsController<string>();

Dealing with collisions

Some times you want multiple types of for the same zod schema type. You can deal with collisions using createUniqueFieldSchema:

const MyUniqueFieldSchema = createUniqueFieldSchema(
  z.string(),
  "aUniqueId" // You need to pass a string ID, it can be anything but has to be set explicitly and be unique.
);

const mapping = [
  [z.string(), NormalTextField] as const,
  [MyUniqueFieldSchema, UltraTextField] as const,
] as const;

const MyFormSchema = z.object({
  mapsToNormal: z.string(), // renders as a NormalTextField component
  mapsToUnique: MyUniqueTextFieldSchema, // renders as a UltraTextField component.
});

Handling Optionals

@ts-react/form will match optionals to their non optional zod schemas:

const mapping = [
  [z.string(), TextField],
] as const

const FormSchema = z.object({
  optionalEmail: z.string().email().optional(), // renders to TextField
  nullishZipCode: z.string().min(5, "5 chars please").nullish() // renders to TextField
})

Your zod-component-mapping should not include any optionals. If you want a reusable optional schema, you can do something like this:

const mapping = [
  [z.string(), TextField],
] as const

export const OptionalTextField = z.string().optional();

Accessing useForm state

Sometimes you need to work with the form directly (such as to reset the form from the parent). In these cases, just pass the react-hook-form useForm() result to your form:

function MyPage() {
  // Need to type the useForm call accordingly
  const form = useForm<z.infer<typeof FormSchema>>();
  const { reset } = form;
  return (
    <Form
      form={form}
      schema={FormSchema}
      // ...
    />
  );
}

Complex field types

You can use most any zod schema and have it map to an appropriate component:

function AddressEntryField() {
  const {field: {onChange, value}, error} = useTsController<z.infer<typeof AddressSchema>>();
  const street = value?.street;
  const zipCode = value?.zipCode;
  return (
    <div>
      <input
        value={street}
        onChange={(e)=>{
          onChange({
            ...value,
            street: e.target.value,
          })
        })
      />
      {error?.street && <span>{error.street.errorMessage}</span>}
      <input
        value={zipCode}
        onChange={(e)=>{
          onChange({
            ...value,
            zipCode: e.target.value
          })
        }}
      />
      {error?.zipCode && <span>{error.zipCode.errorMessage}</span>}
    </div>
  )
}

const AddressSchema = z.object({
  street: z.string(),
  zipCode: z.string(),
});

const mapping = [
  [z.string, TextField] as const,
  [AddressSchema, AddressEntryField] as const,
] as const;

const FormSchema = z.object({
  name: z.string(),
  address: AddressSchema, // renders as AddressInputComponent
});

This allows you to build stuff like this when your designer decides to go crazy:

Adding non input components into your form

Some times you need to render components in between your fields (maybe a form section header). In those cases there are some extra props that you can pass to your fields beforeElement or afterElement which will render a ReactNode before or after the field:

<MyForm
  schema={z.object({
    field: z.string(),
  })}
  props={{
    field: {
      beforeElement: <span>Renders Before The Input</span>,
      afterElement: <span>Renders After The Input</span>,
    },
  }}
/>

Customizing form components

By default your form is just rendered with a "form" tag. You can pass props to it via formProps:

<MyForm
  formProps={{
    ariaLabel: "label",
  }}
/>

You can also provide a custom form component as the second parameter to createTsForm options if you want, it will get passed an onSubmit function, and it should also render its children some where:

const mapping = [
  //...
] as const

function MyCustomFormComponent({
  children,
  onSubmit,
  aThirdProp,
}:{
  children: ReactNode,
  onSubmit: ()=>void,
  aThirdProp: string,
}) {
  return (
    <form onSubmit={onSubmit}>
      <img src={"https://picsum.photos/200"} className="w-4 h-4">
      {/* children is you form field components */}
      {children}
      <button type="submit">submit</button>
    </form>
  )
}
// MyCustomFormComponent is now being used as the container instead of the default "form" tag.
const MyForm = createTsForm(mapping, {FormComponent: MyCustomFormComponent});

<MyForm
  formProps={{
    // formProps is typesafe to your form component's props (and will be required if there is
    // required prop).
    aThirdProp: "prop"
  }}
/>

Manual Form Submission

The default form component as well as a custom form component (if used) will automatically be passed the onSubmit function. Normally, you'll want to pass a button to the renderAfter or renderBefore prop of the form:

<MyForm renderAfter={() => <button type="submit">Submit</button>} />

For React Native, or for other reasons, you will need to call submit explicitly:

<MyForm
  renderAfter={({ submit }) => (
    <TouchableOpacity onPress={submit}>
      <Text>Submit</Text>
    </TouchableOpacity>
  )}
/>

React Native Usage

For now React Native will require you to provide your own custom form component. The simplest way to do it would be like:

const FormContainer = ({ children }: { children: ReactNode }) => (
  <View>{children}</View>
);

const mapping = [
  //...
] as const;

const MyForm = createTsForm(mapping, { FormComponent: FormContainer });

Default values

You can provide typesafe default values like this:

const Schema = z.object({
  string: z.string(),
  num: z.number()
})
//...
<MyForm
  schema={Schema}
  defaultValues={{
    string: 'default',
    num: 5
  }}
/>

Prop Forwarding

Prop forwarding is an advanced feature that allows you to control which props @ts-react/form forward to your components as well as the name.

You probably don't need to use this especially when building a project from scratch, but it can allow more customization. This can be useful for integrating with existing components, or for creating a selection of components that can be used both with and without @ts-react/form.

For example, if I wanted the react hook form control to be forwarded to a prop named floob I would do:

const propsMap = [
  ["control", "floob"] as const,
  ["name", "name"] as const,
] as const;

function TextField({ floob, name }: { floob: Control<any>; name: string }) {
  const { field, fieldState } = useController({ name, control: floob });
}

const componentMap = [[z.string(), TextField] as const] as const;

const MyForm = createTsForm(componentMap, {
  propsMap: propsMap,
});

Props that are included in the props map will no longer be passable via the props prop of the form. So if you don't want to forward any props to your components (and prefer just using hooks), you can pass an empty array. Any data that's not included in the props map will no longer be passed to your components

These allow you to build forms even faster by connecting zod schemas directly to react state. These features are opt-in, it's possible to do the things in this section via props but these approaches may be faster / easier.

Enums

If your schema is mapped using a z.enum(), the enums values will be passed as a prop to the component. This makes it easier is to create things like dropdowns etc:

function DropDownSelect({ enumValues }: { enumValues: string[] }) {
  const {field, error} = useTsController<string>();
  return (
    <>
      <select
        value={field.value?field.value:'none'}
        onChange={(e)=>{
          field.onChange(e.target.value);
        }}
      >
        {!field.value && <option value="none">Please select...</option>}
        {enumValues.map((e) => (
          <option value={e}>{capitalizeFirstLetter(e)}</option>
        ))}
      </select>
      <span>
        {error?.errorMessage && error.errorMessage}
      </span>
    <>
  );
}

const mapping = [
  // The mapping enum values don't matter, they don't get passed to components.
  [z.enum(['placeholder']), DropDownSelect]
] as const;

const MyForm = z.object({
  eyeColor: z.enum(["blue", "brown", "green", "hazel"]),
  favoritePants: z.enum(["jeans", "khakis", "none"]),
});

//...

In the above example, @ts-react/form will render two dropdowns, one with values ['blue', 'brown', 'green', 'hazel'], and on with values ['jeans', 'khakis', 'none'] based on the values passed to the enums.

You can also access these values via the useEnumValues() hook.

Quick Labels / Placeholders

@ts-react/form provides a way to quickly add labels / placeholders via zod's .describe() method:

const FormSchema = z.object({
  // label="Field One", placeholder="Please enter field one...."
  fieldOne: z.string().describe("Field One // Please enter field one..."),
});

The // syntax separates the label and placeholder. @ts-react/form will make these available via the useDescription() hook:

function TextField() {
  const { label, placeholder } = useDescription();
  return (
    <>
      <label>{label}</label>
      <input placeholder={placeholder} />
    </>
  );
}

This is just a quicker way to pass labels / placeholders, but it also allows you to reuse placeholder / labels easily across forms:

const MyTextFieldWithLabel = z.string().describe("label");

const FormSchemaOne = z.object({
  field: MyTextFieldWithLabel,
});

const FormSchemaTwo = z.object({
  field: MyTextFieldWithLabel,
});

If you prefer, you can just pass label and placeholder as normal props via props.

TypeScript versions

Older versions of typescript have worse intellisense and may not show an error in your editor. Make sure your editors typescript version is set to v4.9 plus. The easiest approach is to upgrade your typescript globally if you haven't recently:

sudo npm -g upgrade typescript

Or, in VSCode you can do (Command + Shift + P) and search for "Select Typescript Version" to change your editors Typescript Version:

Screenshot 2023-01-01 at 10 55 11 AM

Note that you can still compile with older versions of typescript and the type checking will work.

Limitations

  • Doesn't support class components
  • @ts-react/form allows you to pass props to your components and render elements in between your components, which is good for almost all form designs out there. Some designs may not be easily achievable. For example, if you need a container around multiple sections of your form, this library doesn't allow splitting child components into containers at the moment. (Though if it's a common-enough use case and you'd like to see it added, open an issue!)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 98.9%
  • JavaScript 1.1%