Top Related Projects
Performance-focused API for React forms 🚀
📋 React Hooks for form state management and validation (Web + React Native)
Build forms in React, without the tears 😭
🏁 High performance subscription-based form state management for React
🤖 Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Lit Form and Vue Form.
Quick Overview
React-ts-form is a TypeScript-based form library for React applications. It leverages TypeScript's type system to provide type-safe form handling, validation, and submission, making it easier to create and manage complex forms in React projects.
Pros
- Strong TypeScript integration for type-safe form handling
- Automatic form state management and validation
- Flexible and customizable, supporting various UI libraries
- Good documentation and examples
Cons
- Learning curve for developers new to TypeScript or advanced type features
- May be overkill for simple forms or small projects
- Limited community support compared to more established form libraries
- Potential performance overhead for very large forms
Code Examples
- Basic form setup:
import { createForm } from "react-ts-form";
const { Form, Field } = createForm<{
name: string;
email: string;
}>();
function MyForm() {
return (
<Form onSubmit={(values) => console.log(values)}>
<Field name="name" />
<Field name="email" />
<button type="submit">Submit</button>
</Form>
);
}
- Custom field component:
import { useField } from "react-ts-form";
function CustomInput({ name }: { name: string }) {
const { value, onChange, onBlur } = useField(name);
return (
<input
value={value}
onChange={(e) => onChange(e.target.value)}
onBlur={onBlur}
/>
);
}
- Form validation:
import { z } from "zod";
import { createForm } from "react-ts-form";
const schema = z.object({
username: z.string().min(3),
password: z.string().min(8),
});
const { Form, Field } = createForm<z.infer<typeof schema>>(schema);
function LoginForm() {
return (
<Form onSubmit={(values) => console.log(values)}>
<Field name="username" />
<Field name="password" type="password" />
<button type="submit">Login</button>
</Form>
);
}
Getting Started
-
Install the package:
npm install react-ts-form zod
-
Create a form schema using Zod:
import { z } from "zod"; const schema = z.object({ name: z.string(), email: z.string().email(), });
-
Create and use the form:
import { createForm } from "react-ts-form"; const { Form, Field } = createForm<z.infer<typeof schema>>(schema); function MyForm() { return ( <Form onSubmit={(values) => console.log(values)}> <Field name="name" /> <Field name="email" /> <button type="submit">Submit</button> </Form> ); }
Competitor Comparisons
Performance-focused API for React forms 🚀
Pros of Unform
- More mature and established project with a larger community
- Supports both React and React Native out of the box
- Offers a more flexible API for complex form scenarios
Cons of Unform
- Steeper learning curve due to its more complex API
- Less TypeScript-focused, which may result in fewer type safety benefits
- Requires more boilerplate code for basic form setups
Code Comparison
Unform:
import React from 'react';
import { Form } from '@unform/web';
import Input from './components/Input';
function MyForm() {
function handleSubmit(data) {
console.log(data);
}
return (
<Form onSubmit={handleSubmit}>
<Input name="email" />
<Input name="password" type="password" />
<button type="submit">Submit</button>
</Form>
);
}
React-ts-form:
import { createTsForm } from 'react-ts-form';
import { z } from 'zod';
const schema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
const MyForm = createTsForm(schema);
function FormComponent() {
return (
<MyForm onSubmit={(values) => console.log(values)}>
{({ email, password }) => (
<>
<email.Field />
<password.Field type="password" />
<button type="submit">Submit</button>
</>
)}
</MyForm>
);
}
📋 React Hooks for form state management and validation (Web + React Native)
Pros of react-hook-form
- More mature and widely adopted, with a larger community and ecosystem
- Offers more advanced features like form validation and error handling out of the box
- Provides better performance optimization for large forms
Cons of react-hook-form
- Steeper learning curve, especially for beginners
- Less TypeScript-focused, which may lead to type-related issues in complex scenarios
- Requires more boilerplate code for basic form setups
Code Comparison
react-hook-form:
import { useForm } from 'react-hook-form';
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} />
<input {...register("lastName")} />
<input type="submit" />
</form>
react-ts-form:
import { createForm } from 'react-ts-form';
const { Form, Field } = createForm<{ firstName: string; lastName: string }>();
<Form onSubmit={data => console.log(data)}>
<Field name="firstName" />
<Field name="lastName" />
<button type="submit">Submit</button>
</Form>
react-ts-form provides a more TypeScript-centric approach with less boilerplate, while react-hook-form offers more flexibility and advanced features at the cost of additional setup.
Build forms in React, without the tears 😭
Pros of Formik
- More mature and widely adopted, with a larger community and ecosystem
- Extensive documentation and examples available
- Flexible and works well with both JavaScript and TypeScript projects
Cons of Formik
- Steeper learning curve for beginners
- Can be overkill for simple form implementations
- Less TypeScript-focused compared to react-ts-form
Code Comparison
react-ts-form:
const { Form } = createForm({
schema: z.object({
name: z.string().min(2),
email: z.string().email(),
}),
});
Formik:
<Formik
initialValues={{ name: '', email: '' }}
validationSchema={Yup.object({
name: Yup.string().min(2, 'Too Short!').required('Required'),
email: Yup.string().email('Invalid email').required('Required'),
})}
onSubmit={values => {
// Handle form submission
}}
>
{/* Form fields */}
</Formik>
react-ts-form focuses on TypeScript integration and type safety, using Zod for schema validation. Formik uses Yup for validation and provides a more verbose but flexible API. react-ts-form offers a more concise syntax for form creation, while Formik requires more boilerplate but offers greater customization options.
🏁 High performance subscription-based form state management for React
Pros of react-final-form
- More mature and widely adopted in the React community
- Extensive documentation and examples available
- Supports both synchronous and asynchronous validation out of the box
Cons of react-final-form
- Steeper learning curve due to its flexibility and advanced features
- Requires more boilerplate code for basic form setups
- Less TypeScript-friendly compared to react-ts-form
Code Comparison
react-final-form:
import { Form, Field } from 'react-final-form'
<Form
onSubmit={onSubmit}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field name="firstName" component="input" placeholder="First Name" />
<button type="submit">Submit</button>
</form>
)}
/>
react-ts-form:
import { createForm } from 'react-ts-form'
const { Form, Field } = createForm<FormSchema>()
<Form onSubmit={onSubmit}>
<Field name="firstName" component="input" placeholder="First Name" />
<button type="submit">Submit</button>
</Form>
The code comparison shows that react-ts-form offers a more concise and TypeScript-friendly syntax, while react-final-form provides a more flexible render prop approach. react-ts-form's type inference capabilities make it easier to work with complex form structures in TypeScript projects, whereas react-final-form requires additional type annotations for full TypeScript support.
🤖 Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Lit Form and Vue Form.
Pros of TanStack Form
- More comprehensive and feature-rich, offering advanced form management capabilities
- Better performance optimization, especially for large and complex forms
- Extensive documentation and community support
Cons of TanStack Form
- Steeper learning curve due to its complexity and advanced features
- Potentially overkill for simple form implementations
- Requires more setup and configuration compared to react-ts-form
Code Comparison
react-ts-form:
import { createForm } from 'react-ts-form';
const MyForm = createForm({
firstName: z.string(),
lastName: z.string(),
});
TanStack Form:
import { useForm } from '@tanstack/react-form';
const form = useForm({
defaultValues: {
firstName: '',
lastName: '',
},
onSubmit: async (values) => {
// Handle form submission
},
});
Both libraries aim to simplify form management in React applications, but they differ in their approach and feature set. react-ts-form focuses on type-safe form creation with minimal setup, while TanStack Form offers a more robust and flexible solution for complex form scenarios. The choice between the two depends on the specific requirements of your project and the level of control you need over form behavior.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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
andreact-hook-form
- ð¤ð» Very tiny utility library (~3kb gzipped)
- ð Great test coverage
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.number(), NumberField],
] 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).
Full Documentation
You can read the full docs here
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:
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
does not yet support "dependent field props", meaning you can't change one field component based on the value of another, but it's a feature we plan on adding soon.
Top Related Projects
Performance-focused API for React forms 🚀
📋 React Hooks for form state management and validation (Web + React Native)
Build forms in React, without the tears 😭
🏁 High performance subscription-based form state management for React
🤖 Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Lit Form and Vue Form.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot