formComponents - typing useFormContext #1335
Unanswered
chrislicodes
asked this question in
Q&A
Replies: 1 comment
-
I wish there was a better way to do this without type assertions, but this does work in the mean time Exampleuse-form.tsx export const { fieldContext, formContext, useFieldContext, useFormContext } =
createFormHookContexts();
export const { useAppForm } = createFormHook({
fieldContext,
formContext,
fieldComponents: {
...
},
formComponents: {
SubmitButton: FormSubmitButton,
CancelButton: FormCancelButton,
SaveChangesV1: SaveChangesV1,
},
});
export type UseAppForm = ReturnType<typeof useAppForm>; SaveChangesV1.tsx import { useFormContext, UseAppForm } from "@/shared/hooks/use-app-form";
import { motion } from "motion/react";
interface FormSubmitButtonProps {
submitText: string;
cancelText: string;
}
const SaveChangesV1 = ({ cancelText, submitText }: FormSubmitButtonProps) => {
const form = useFormContext() as unknown as UseAppForm; // <---- assert the type here
return (
<form.Subscribe
selector={(s) => ({
isDirty: s.isDirty,
isValid: s.isValid,
})}
children={({ isDirty, isValid }) => {
if (isDirty && isValid) {
return (
<motion.div
initial={{
scaleY: 0,
}}
animate={{
scaleY: 1,
}}
className="flex w-full items-center justify-end space-x-2"
>
<form.CancelButton label={cancelText} />
<form.SubmitButton label={submitText} />
</motion.div>
);
} else return null;
}}
/>
);
};
export default SaveChangesV1; form.tsx export const MyForm = () => {
const form = useAppForm({
defaultValues,
});
// don't forget to wrap it in AppForm for the context
return (
<form>
<form.AppForm>
<form.SaveChangesV1 cancelText="Cancel" submitText="Submit Text" />
</form.AppForm>
</form>
)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi there,
I need to create a reusable form component that includes several nested sub-forms. The reason behind this is that I have a deeply nested object structure, and the same interface can appear at multiple paths within the object.
Is it possible to type the
useFormContext
so that it expects the typeMainObject
?For instance:
Any pointers or suggestions would be greatly appreciated. Thanks!
Related: #1175
Beta Was this translation helpful? Give feedback.
All reactions