-
-
Notifications
You must be signed in to change notification settings - Fork 780
/
Form.tsx
62 lines (56 loc) · 1.64 KB
/
Form.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
import React, {ReactNode, PropsWithoutRef} from "react"
import {Form as FinalForm, FormProps as FinalFormProps} from "react-final-form"
import * as z from "zod"
export {FORM_ERROR} from "final-form"
type FormProps<FormValues> = {
/** All your form fields */
children: ReactNode
/** Text to display in the submit button */
submitText: string
onSubmit: FinalFormProps<FormValues>["onSubmit"]
initialValues?: FinalFormProps<FormValues>["initialValues"]
schema?: z.ZodType<any, any>
} & Omit<PropsWithoutRef<JSX.IntrinsicElements["form"]>, "onSubmit">
export function Form<FormValues extends Record<string, unknown>>({
children,
submitText,
schema,
initialValues,
onSubmit,
...props
}: FormProps<FormValues>) {
return (
<FinalForm<FormValues>
initialValues={initialValues}
validate={(values) => {
if (!schema) return
try {
schema.parse(values)
} catch (error) {
return error.formErrors.fieldErrors
}
}}
onSubmit={onSubmit}
render={({handleSubmit, submitting, submitError}) => (
<form onSubmit={handleSubmit} className="form" {...props}>
{/* Form fields supplied as children are rendered here */}
{children}
{submitError && (
<div role="alert" style={{color: "red"}}>
{submitError}
</div>
)}
<button type="submit" disabled={submitting}>
{submitText}
</button>
<style global jsx>{`
.form > * + * {
margin-top: 1rem;
}
`}</style>
</form>
)}
/>
)
}
export default Form