-
Notifications
You must be signed in to change notification settings - Fork 84
/
collection.tsx
85 lines (77 loc) · 2.33 KB
/
collection.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { getCollectionProps, getFormProps, useForm } from '@conform-to/react';
import { parseWithZod } from '@conform-to/zod';
import {
type LoaderFunctionArgs,
type ActionFunctionArgs,
json,
} from '@remix-run/node';
import { Form, useActionData, useLoaderData } from '@remix-run/react';
import { z } from 'zod';
import { Playground, Field } from '~/components';
const schema = z.object({
singleChoice: z.string({ required_error: 'Required' }),
multipleChoice: z
.enum(['a', 'b', 'c'], {
errorMap(issue, ctx) {
if (issue.code === 'invalid_enum_value') {
return { message: 'Invalid' };
}
return {
message: ctx.defaultError,
};
},
})
.array()
.min(1, 'Required'),
});
export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
return {
noClientValidate: url.searchParams.get('noClientValidate') === 'yes',
};
}
export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const submission = parseWithZod(formData, { schema });
return json(submission.reply());
}
export default function Example() {
const { noClientValidate } = useLoaderData<typeof loader>();
const lastResult = useActionData<typeof action>();
const [form, fields] = useForm({
id: 'collection',
lastResult,
shouldRevalidate: 'onInput',
onValidate: !noClientValidate
? ({ formData }) => parseWithZod(formData, { schema })
: undefined,
});
return (
<Form method="post" {...getFormProps(form)}>
<Playground title="Collection" result={lastResult}>
<Field label="Single choice" meta={fields.singleChoice}>
{getCollectionProps(fields.singleChoice, {
type: 'radio',
options: ['x', 'y', 'z'],
}).map((props) => (
<label key={props.value} className="inline-block">
<input {...props} />
<span className="p-2">{props.value?.toUpperCase()}</span>
</label>
))}
</Field>
<Field label="Multiple choice" meta={fields.multipleChoice} allErrors>
{getCollectionProps(fields.multipleChoice, {
type: 'checkbox',
options: ['a', 'b', 'c', 'd'],
}).map((props) => (
<label key={props.value} className="inline-block">
<input {...props} />
<span className="p-2">{props.value?.toUpperCase()}</span>
</label>
))}
</Field>
</Playground>
</Form>
);
}