iway1 / react-ts-form

https://react-ts-form.com
MIT License
2.01k stars 33 forks source link

Accessing the submitter element? (multiple submit buttons) #111

Open AlbertoV5 opened 1 year ago

AlbertoV5 commented 1 year ago

Question/Feature Request: Accessing the submitter element (button)

Hello. Sorry if this is specified on the docs or other issue, I wasn't able to find it by looking for 'submitter' or 'submit', etc. Is there a way to access the submitter element from the onSubmit function?. For example:

In the case of having multiple submit buttons for different actions with the same form state:

return (
...
<ul className="dropdown-menu dropdown-menu-dark bg-dark border-primary">
  {
      ['save', 'save as'].map((name) => (
          <li key={name}>
              <button
                  type="submit"
                  name={name}
                  value={name}
                  className="dropdown-item dropdown-item-dark"
              >{name}</button>
          </li>
          )
      )
  }
</ul>
...
)

The current way to get the event data is to store outside of the form component

export function FormContainer({
    id,
    onSubmit,
    children,
    header,
}: {
    id: string;
    onSubmit: () => void;
    children: ReactNode;
    header: string;
}) {
    const { action } = useAction();
    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        action.name = ((event.nativeEvent as SubmitEvent).submitter as HTMLInputElement).name;
        onSubmit();
    }
    ...

And then the parent component can use the submitter value:

...
    const { action } = useAction();
    const submitPreset = (data: z.infer<typeof forms.preset>) => {
        console.log(action);
        console.log(data);
    };
...

It doesn't seem ideal, is the event available to the Form's parent element via any callback or form state? Can I modify the callback to include it? How could someone go about supporting multiple submit options? Haven't been able to find info. about it in the docs.

Thank you, very good library :)

bartoszgolebiowski commented 1 year ago

It seems like this is the react-hook-form issue, I found this interesting article about resolving this kind of issue. Check this out! https://stackoverflow.com/a/69025391

All form fields are under: <FormProvider>{}</FormProvider> from import {FormProvider} from "react-hook-form" https://react-hook-form.com/api/formprovider/ so I think submit method is available here: useFormContext https://react-hook-form.com/api/useformcontext/

AlbertoV5 commented 1 year ago

Thank you! Will check that out :) For some reason the react hook form hooks give me a 404, these work: https://react-hook-form.com/docs/useformcontext