Why does a react onClick event append a question mark to my url?

后端 未结 2 1384
时光取名叫无心
时光取名叫无心 2021-02-08 00:03

For some reason my onClick handlers are adding an empty query param to my url when I click them. I was able to fix the issue by adding event.preventDefault to my event handlers

相关标签:
2条回答
  • 2021-02-08 00:19

    I am pretty sure that since you are capturing the click of a button from a form, without the preventDefault() the form is posting. Since there are no inputs in the form there are no query parameters. Since the form doesn't specify the POST method it is doing a get request back to itself which is adding an empty query string. With the preventDefault() you are stopping the form submit action.

    0 讨论(0)
  • 2021-02-08 00:22

    The default type of a button tag is submit which means clicking the button will submit your form (appending the ? to your url).

    To fix your example, you can add type="button" to your buttons &/or replace your <form> with a <div>/<span> (since your code doesn't really seem to need the form element).

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

    Possible values are:

    • submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is
      dynamically changed to an empty or invalid value.
    • reset: The button resets all the controls to their initial values.
    • button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
    0 讨论(0)
提交回复
热议问题