ApathyBear ApathyBear - 1 year ago 90
Node.js Question

react/jquery: redirecting to another URL with built query string

I have an input a simple input box within a render statement in my react component that looks like this:

<form onSubmit={this.handleSubmit}>
<input id="searchbox" type="text" />

Using the
function, I would like to redirect the contents of the
to another URL endpoint on my site. Specifically I would like to forward it to
with the contents in the form of a query string, like so:


What is the best way to redirect to within handleSubmit()? Here is my pseudocode:

// contents of search box
var val = $('#searchbox').val();

//Create querystring
var queryString = makeQueryString(val)

//redirect to /confidence endpoint with built querystring
redirect('/confidence' + queryString)

Answer Source

Redirecting: as simple as calling location.href = newUrlString

However, form submitting appears to take precedence so you need to prevent default behaviour.

handSubmit(event) {
  location.href = newUrlString

Getting values from forms in React:

There's no need to use jQuery here just to get form values in a React component.. if we needed that then why use React at all? Use the ref callback function to store the node after the page has loaded, and pass the value to your submit handler.

<form onSubmit={event => this.handleSubmit(event, this.inputNode.value)}>
  <input ref={node => this.inputNode = node} type="text" />