最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - submit child form that was inside another form and prevent submitting parent form, react-hook-form - Stack Overflow

programmeradmin6浏览0评论

I am in the situation that I have to run function while submitting child form that was located inside another form and while I was submitting child form, parent form also running submit function, I give different id's and htmlFor of form attributes for the form but problem is not being solved. I am using react-hook-form

I am in the situation that I have to run function while submitting child form that was located inside another form and while I was submitting child form, parent form also running submit function, I give different id's and htmlFor of form attributes for the form but problem is not being solved. I am using react-hook-form

Share Improve this question asked Aug 17, 2022 at 7:25 AliIbnBotirAliIbnBotir 1031 gold badge2 silver badges6 bronze badges 4
  • 1 Hope this link will be helpful to you. Link) – Syum Akhlaque Commented Aug 17, 2022 at 10:47
  • 2 Does this answer your question? React JS Multiple submit Buttons react-hook-form – Mark Rotteveel Commented Apr 23, 2023 at 11:08
  • @MarkRotteveel Yes, it does. Actually, I saw that answer a long time ago and 2 days ago I added the answer to this question, but it got deleted by review. I didn't understand why?. Anyway, thanks for the help. – AliIbnBotir Commented Apr 24, 2023 at 19:57
  • Because your answer was basically only a link. You should accept the duplicate, so your question is closed as a duplicate to that other question. – Mark Rotteveel Commented Apr 25, 2023 at 8:51
Add a ment  | 

2 Answers 2

Reset to default 6

In my case, the issue was that my form looked like this when the issue occurred:

const MyComponent = () => {
  const form = useForm({...});

  const onSubmit = () => {...}

  return <Form {...form}>
    <form onSubmit={form.handleSubmit(onSubmit)}>
      
    </form>
  </Form>

}

I found online that this was fixable by doing e.stopPropagation(), and to do that, I changed the <form> onSubmit argument to:

<form onSubmit={(e) => {
    e.preventDefault();
    e.stopPropagation();
    form.handleSubmit(onSubmit)
  } }
>

But I forgot to call the actual handler. Correct code:

<form onSubmit={(e) => {
    e.preventDefault();
    e.stopPropagation();
    form.handleSubmit(onSubmit)(); // key is the () in the end
  } }
>

It's happening due to the event propagating. I've encountered and resolved this issue, so sharing my solution might help you too.

  • Solution 1

use the stopPropagation to avoid unintended Actions

<form
  onSubmit={(e) => {
    e.stopPropagation();
    return handleSubmit(yourSubmitFunction)(e);
  }}
  id={formId}
>
  Your Form Content
</form>
  • Solution 2

Remove the type = "submit" from your button.

<button onClick={() => handleSubmit()}> submit </button>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论