Why does an onClick event response add a question mark to my url?

For some reason, my onClick handlers add an empty request parameter to my URL when I click on them. I was able to fix the problem by adding event.preventDefault to my event handlers, but I would like to better understand what actually happened and if that was the right solution. For context, the code below is a simple component to test some OAuth 2 functions. OnClick handlers simply invoke the reflux action. You will see that I added e.preventDefault () to all of them. Without this fix, at any time when I run one of these functions, my url will change from http: // localhost: 3000 / # / signIn to http: // localhost: 3000 /? # / SignIn . I also use a jet router.

// dependencies ------------------------------------------------------- import React from 'react'; import hello from '../../libs/hello'; import Actions from '../../actions/Actions'; import UserStore from '../../stores/userStore'; var Signin = React.createClass({ // life cycle events -------------------------------------------------- componentDidMount: function () { }, render: function () { return ( <form> <h2>Sign in with Google</h2> <button className="btn btn-primary" onClick={this._signIn} > <i className="fa fa-google" /> <span> Google</span> </button> <button className="btn btn-info" onClick={this._logToken} >Log Token</button> <button className="btn btn-warning" onClick={this._signOut}>Sign Out</button> </form> ); }, // custom methods ----------------------------------------------------- _signIn: function (e) { e.preventDefault(); Actions.signIn(); }, _signOut: function (e) { e.preventDefault(); Actions.signOut(); }, _logToken: function (e) { // e.preventDefault(); Actions.logToken(); } }); export default Signin; 
+6
source share
2 answers

The default button tag type button means that clicking button will submit your form (by adding ? To your URL).

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

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

Possible values:

  • submit: the button submits the form data to the server. This is the default value if no attribute is specified or the is attribute is dynamically changed to a null or invalid value.
  • reset: the button resets all controls to their initial values.
  • : The button has no default behavior. It may have client scripts associated with element events that fire when events occur.
+17
source

I am sure that since you capture a button click from a form, without warning, it does not publish the form. Since there is no input in the form, there are no query parameters. Since the form does not specify a POST method, it returns a get request to itself, which adds an empty request line. With preventDefault () you stop the form submit action.

+6
source

Source: https://habr.com/ru/post/988040/


All Articles