Forms
Collect and validate user input with ease.
Overview
LibreApps Desktop provides a set of form components built on top of React Hook Form and Zod. This combination ensures that your forms are easy to manage, highly performant, and have robust validation.
Usage
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
const formSchema = z.object({
username: z.string().min(2).max(50),
})
export function MyForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
username: "",
},
})
function onSubmit(values: z.infer<typeof formSchema>) {
console.log(values)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="shadcn" {...field} />
</FormControl>
<FormDescription>
This is your public display name.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
)
}
Components
- Form: The main wrapper that provides the form context.
- FormField: A controlled component that manages a single form field.
- FormItem: A container for a label, control, description, and message.
- FormLabel: The label for the form field.
- FormControl: The wrapper for the actual input component (e.g.,
Input,Select). - FormDescription: Optional help text for the field.
- FormMessage: Displays validation errors.
Best Practices
- ✅ Do this: Use Zod schemas to define your form's data structure and validation rules.
- ✅ Do this: Provide clear and helpful error messages for all validation failures.
- ❌ Don't do this: Manually manage form state using
useState; use React Hook Form for better performance and developer experience.