Skip to content

Commit

Permalink
Merge pull request #79 from LandSprutte/main
Browse files Browse the repository at this point in the history
Expose formState for children as render prop
  • Loading branch information
vantezzen authored Jun 6, 2024
2 parents 2a37f85 + 7fa5e7c commit b63a087
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ const formSchema = z.object({
z.object({
name: z.string(),
age: z.coerce.number(),
})
}),
)
// Optionally set a custom label - otherwise this will be inferred from the field name
.describe("Guests invited to the party"),
Expand All @@ -384,7 +384,7 @@ const formSchema = z.object({
z.object({
name: z.string(),
age: z.coerce.number(),
})
}),
)
.describe("Guests invited to the party")
.default([
Expand Down
13 changes: 10 additions & 3 deletions src/components/ui/auto-form/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";
import { Form } from "@/components/ui/form";
import React from "react";
import { DefaultValues, useForm } from "react-hook-form";
import { DefaultValues, FormState, useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
Expand Down Expand Up @@ -49,7 +49,9 @@ function AutoForm<SchemaType extends ZodObjectOrWrapped>({
onParsedValuesChange?: (values: Partial<z.infer<SchemaType>>) => void;
onSubmit?: (values: z.infer<SchemaType>) => void;
fieldConfig?: FieldConfig<z.infer<SchemaType>>;
children?: React.ReactNode;
children?:
| React.ReactNode
| ((formState: FormState<z.infer<SchemaType>>) => React.ReactNode);
className?: string;
dependencies?: Dependency<z.infer<SchemaType>>[];
}) {
Expand Down Expand Up @@ -82,6 +84,11 @@ function AutoForm<SchemaType extends ZodObjectOrWrapped>({
}
}, [valuesString]);

const renderChildren =
typeof children === "function"
? children(form.formState as FormState<z.infer<SchemaType>>)
: children;

return (
<div className="w-full">
<Form {...form}>
Expand All @@ -98,7 +105,7 @@ function AutoForm<SchemaType extends ZodObjectOrWrapped>({
fieldConfig={fieldConfig}
/>

{children}
{renderChildren}
</form>
</Form>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/examples/Array.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const formSchema = z.object({
z.object({
name: z.string(),
age: z.coerce.number(),
})
}),
)
.describe("Guests invited to the party"),
});
Expand Down

0 comments on commit b63a087

Please sign in to comment.