I have a complex form and I want to implement a hardSubmit method like this.
It works good, The problem is I don´t know how add this method as valid whit TS
const Form=()=>{
const hardSubmit = () => {
console.log('hard submit');
setFormStatus(FORM_LABELS.loading);
handleSubmit((props: any) => {
console.log('submit');
onSubmit(props);
})();
};
Return(
<FormProvider {...methods} hardSubmit={hardSubmit}> //<--- TS don´t allow me add "add hardSubmit"
<form
onSubmit={handleSubmit((data: any) => onSubmit(data))
>
// ... nested compoonents
</form>
</FormProvider>
)}
https://react-hook-form.com/api/useformcontext/
CodePudding user response:
As I mentioned in my comment; you could create your own FormProvider
component which extends the default FormProviderProps
and the custom hardSubmit you want to add.
import { FC } from "react";
import { FormProvider, FormProviderProps } from "react-hook-form";
interface Props extends FormProviderProps<any, any> {
hardSubmit: () => void;
}
export const MyFormProvider: FC<Props> = ({
children,
hardSubmit,
...formProps
}) => {
return (
<FormProvider {...formProps}>
{children}
<button onClick={hardSubmit}>hard submit</button>
</FormProvider>
);
};
You could use this like
import { useForm } from "react-hook-form";
import "./styles.css";
import { MyFormProvider } from "./MyFormProvider";
export default function App() {
const methods = useForm();
const hardSubmit = () => {
console.log("hard submit");
};
return (
<MyFormProvider {...methods} hardSubmit={hardSubmit}>
<form onSubmit={methods.handleSubmit(console.log, console.log)}>
<input placeholder="test" {...methods.register("name")} />
<button type="submit">submit</button>
</form>
</MyFormProvider>
);
}
Have a look at this codesandbox for a working example