ApathyBear ApathyBear - 5 months ago 42
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:

render()
return(
<form onSubmit={this.handleSubmit}>
<input id="searchbox" type="text" />
</form>
);


Using the
this.handleSubmit
function, I would like to redirect the contents of the
<input>
to another URL endpoint on my site. Specifically I would like to forward it to
www.mysite.com/confidence
with the contents in the form of a query string, like so:

www.mysite.com/SB=?the%query%string


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

handleSubmit(){
// 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

Redirecting: as simple as calling location.href = newUrlString

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

handSubmit(event) {
  event.preventDefault()
  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" />
</form>