简体   繁体   中英

Submit button is refreshing the page instead of submitting the form? (ReactJS and react-toastify)

As the title says, I have two buttons that have the exact same format, but one is refreshing the page when clicked instead of submitting the form. I just need it to trigger a toast.

Here's the working button:

<button
    type="submit"
    className="btn btn-primary my-2 my-sm-0"
    style={{ marginTop: "10px" }}
    onClick={() => onSubmit()}
>
  <i className="fas fa-search"></i>
</button>

And here is the not working button:

<button
    type="submit"
    className="btn btn-primary my-2 my-sm-0"
    style={{ marginTop: "10px" }}
    onClick={() => onSubmit()}
>
    <i className="fas fa-paper-plane"></i>
</button>

The only difference is the first one is wrapped in a Link tag to submit a search, while the other will be submitting an email to subscribe to a newsletter, but it should just trigger a toast for now.

Help?

Also, I've tried event.preventDefault already (didn't work), and both are in the exact same form format as well.

Don't mix button type="submit" and an onClick handler as this will submit the associated form and take any default form submission actions.

Also, I've tried event.preventDefault already (didn't work), and both are in the exact same form format as well.

This didn't work because your onSubmit callback wasn't receiving the event object.

Either change the type to "button" and use the onClick handler to do the form data submission

<button
    type="button" // <-- button type
    className="btn btn-primary my-2 my-sm-0"
    style={{ marginTop: "10px" }}
    onClick={onSubmit}
>
  <i className="fas fa-search"></i>
</button>

Or move the onSubmit handler to the form from the button

<form onSubmit={onSubmit} ...>
  ...

  <button
      type="submit"
      className="btn btn-primary my-2 my-sm-0"
      style={{ marginTop: "10px" }}
  >
    <i className="fas fa-search"></i>
  </button>

  ...

</form>

You need to also attach the onSubmit to either element in a way that it also consumes the event so you can event.preventDefault() on it.

Either

onSubmit={e => onSubmit(e)}
onClick={e => onSubmit(e)}

or

onSubmit={onSubmit}
onClick={onSubmit}

And remember to actually call event.preventDefault()

const onSubmit = e => {
  e.preventDefault();
  ...
}

If you've still further issues because of the link wrapping then you can also invoke event.stopPropgation() in the handler to prevent the event from bubbling up the DOM ( virtualDOM in this case because react uses synthetic events ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM