user3033194 user3033194 - 5 months ago 10
Javascript Question

React property not appearing as query parameter

I have a small form which I am using to pass a value in through URL (as a query parameter). The form is given below:

<form method="GET">
<input type="hidden" value={`${this.props.age}`} name="p" />
<a href="profile" class="btn btn-primary" type="submit">View</a>
</form>


The idea is to access the age value from the URL in the new page. Something like:

http://localhost:8000/?age=13


However, when I am clicking the link, no query parameter appears in the URL. Does someone know how this can be fixed? Thanks in advance!!

Answer

I think you should use <button> instead of <a>., because when you click on View you go to /profile/ page (href has property /profile/) but not submit form to server. type attribute for button and a have different meaning

button - The type attribute specifies the type of button.

a - The type attribute specifies the Internet media type (formerly known as MIME type) of the linked document.

<form method="GET">
  <input type="hidden" value={`${this.props.age}`} name="p" />
  <button className="btn btn-primary" type="submit">View</button>
</form>

Example


also you can trigger submit method, and prevent default action for <a>

var App = React.createClass({
  submit: function (e) {
    e.preventDefault();
    this.refs.form.submit();
  },

  render: function() {
    return <form method="GET" ref="form">
      <input type="hidden" value={`${this.props.age}`} name="p" />
      <a href="profile" class="btn btn-primary" onClick={ this.submit }>View</a>   
    </form>;
  }
});

Example