Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

app.formComponents.tsx

84 lines1.8 KB

1import { useStore } from "@tanstack/react-form";
2import { useId } from "react";
3import { useFieldContext } from "@/hooks/app.form-context";
4import { Input } from "./ui/input";
5import { Label } from "./ui/label";
6import { Textarea as ShadcnTextarea } from "./ui/textarea";
7​
8function ErrorMessages({
9 errors,
10}: {
11 errors: Array<string | { message: string }>;
12}) {
13 return (
14 <>
15 {errors.map((error) => (
16 <div
17 key={typeof error === "string" ? error : error.message}
18 className="text-sm text-red-500 mt-1"
19 >
20 {typeof error === "string" ? error : error.message}
21 </div>
22 ))}
23 </>
24 );
26​
27export function TextField({
28 label,
29 placeholder,
30}: {
31 label: string;
32 placeholder?: string;
33}) {
34 const field = useFieldContext<string>();
35 const errors = useStore(field.store, (state) => state.meta.errors);
36​
37 const id = useId();
38​
39 return (
40 <div>
41 <Label className="mb-2" htmlFor={id}>
42 {label}
43 </Label>
44 <Input
45 id={id}
46 value={field.state.value}
47 placeholder={placeholder}
48 onBlur={field.handleBlur}
49 onChange={(e) => field.handleChange(e.target.value)}
50 />
51​
52 {field.state.meta.isTouched && <ErrorMessages errors={errors} />}
53 </div>
54 );
56​
57export function TextArea({
58 label,
59 rows = 3,
60}: {
61 label: string;
62 rows?: number;
63}) {
64 const field = useFieldContext<string>();
65 const errors = useStore(field.store, (state) => state.meta.errors);
66​
67 const id = useId();
68​
69 return (
70 <div>
71 <Label htmlFor={id} className="mb-2">
72 {label}
73 </Label>
74 <ShadcnTextarea
75 id={id}
76 value={field.state.value}
77 onBlur={field.handleBlur}
78 rows={rows}
79 onChange={(e) => field.handleChange(e.target.value)}
80 />
81 {field.state.meta.isTouched && <ErrorMessages errors={errors} />}
82 </div>
83 );