user3033194
user3033194

Reputation: 1831

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!!

Upvotes: 1

Views: 59

Answers (3)

Oleksandr T.
Oleksandr T.

Reputation: 77502

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

Upvotes: 3

Cth103
Cth103

Reputation: 73

The <a> tag only redirect to a page. Then you may want to add some css code to make the button look like an <a> tag.

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

Upvotes: 1

omerts
omerts

Reputation: 8838

An <a> tag doesn't submit your form, only redirects to a different url.

The following should work:

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

Upvotes: 1

Related Questions