diff --git a/packages/@next-fetch/react-query/src/form.ts b/packages/@next-fetch/react-query/src/form.ts index 4ab7724..38cf5bc 100644 --- a/packages/@next-fetch/react-query/src/form.ts +++ b/packages/@next-fetch/react-query/src/form.ts @@ -1,4 +1,4 @@ -import { type HTMLProps, createElement } from "react"; +import { type HTMLProps, createElement, forwardRef } from "react"; import { useForm as useForm_ } from "@next-fetch/core-plugin/form"; import type { UseMutationResult, @@ -32,15 +32,30 @@ export function useForm( * This enables progressive enhancement, as the form can be submitted * without having to re-render the app using JavaScript code. */ -export function Form({ - mutation, - mutationConfig, - ...props -}: React.HTMLProps & +type FormProps = React.HTMLProps & React.PropsWithChildren<{ mutation: HookWithFormSubmission; mutationConfig?: UseMutationOptions; - }>) { + }>; + +type FormT = ( + props: FormProps & { + ref?: React.ForwardedRef; + } +) => ReturnType; + +export function FormImpl( + { + mutation, + mutationConfig, + ...props + }: FormProps, + ref: React.ForwardedRef +) { const { formProps } = useForm(mutation, mutationConfig); - return createElement("form", { ...formProps, ...props }, props.children); + + return createElement("form", { ...formProps, ...props, ref }, props.children); } + +// 1. https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref/58473012#58473012 +export const Form = forwardRef(FormImpl) as unknown as FormT; diff --git a/packages/@next-fetch/swr/src/form.ts b/packages/@next-fetch/swr/src/form.ts index be965c9..282f94e 100644 --- a/packages/@next-fetch/swr/src/form.ts +++ b/packages/@next-fetch/swr/src/form.ts @@ -1,4 +1,4 @@ -import { type HTMLProps, createElement } from "react"; +import { type HTMLProps, createElement, forwardRef } from "react"; import { useForm as useForm_ } from "@next-fetch/core-plugin/form"; import type { SWRMutationResponse, @@ -32,15 +32,24 @@ export function useForm( * This enables progressive enhancement, as the form can be submitted * without having to re-render the app using JavaScript code. */ -export function Form({ - mutation, - mutationConfig, - ...props -}: React.HTMLProps & +type FormProps = React.HTMLProps & React.PropsWithChildren<{ mutation: HookWithFormSubmission; mutationConfig?: SWRMutationConfiguration; - }>) { + }>; + +type FormT = ( + props: FormProps & { ref?: React.ForwardedRef } +) => ReturnType; + +function FormImpl( + { mutation, mutationConfig, ...props }: FormProps, + ref?: React.ForwardedRef +) { const { formProps } = useForm(mutation, mutationConfig); - return createElement("form", { ...formProps, ...props }, props.children); + + return createElement("form", { ...formProps, ...props, ref }, props.children); } + +// 1. https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref/58473012#58473012 +export const Form = forwardRef(FormImpl) as unknown as FormT;