Quick start
Start integration hookform-field in under 5 minutes
Get started
Welcome to hookform-field documentation guide. Follow the instructions below to learn how to install, integrate to your projects
Installation
First, install the package via npm/yarn/pnpm:
# npm
npm install hookform-field react-hook-form
# yarn
yarn add hookform-field react-hook-form
# pnpm
pnpm install hookform-field react-hook-form
Usage
Step 1: Define Your Custom Fields
You can create custom form fields by using the createField
function. For example, to create text, number, file, and select fields:
// Example: <home>/<your-project>/src/components/form/field.tsx
import React from "react";
import { createField } from "hookform-field";
import TextInput from "components/text-input";
import NumberInput from "components/number";
import Select from "components/select";
import Otp from "components/otp";
const Field = createField({
text: TextInput,
number: NumberInput,
select: Select,
otp: Otp
});
export default Field;
Step 2: Create Your Form
Next, create a form using the Form
component and include your custom fields:
import React from "react";
import { Form } from "hookform-field";
import Field from "@/components/form/field"; // Import the Field component you created
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod" // Import your resolver from hookform
const schema = z.object({
name: z.string(),
amount: z.number(),
avatar: z.any(),
age: z.string(),
})
type SchemaInferred = z.infer<typeof schema>
const resolver = zodResolver(schema)
const MyForm = () => {
return (
// `useForm` wrapped by <Form /> of hookform-field help you save time define it
<Form<SchemaInferred>
resolver={resolver}
defaultValues={{ name: "Bob" }}
onSubmit={(values) => console.log(values)} // <-- type-safe / infer type
>
<Field label="Name" component="text" name="name" />
<Field component="number" name="amount" />
<Field label="File" component="file" name="avatar" />
<Field component="select" name="age" options={[{ value: '1', label: '1' }, { value: '2', label: '2' }]} />
</Form>
);
};
export default MyForm;
The <Field />
component will be type-safe based on your component values, suggesting the correct props based on the component props.
Step 3: Render Your Form
Finally, render your form in your application:
import React from "react";
import ReactDOM from "react-dom";
import MyForm from "./MyForm"; // Import the MyForm component you created
const App = () => {
return (
<div>
<h1>My Custom Form</h1>
<MyForm />
</div>
);
};