kbang
kbang

Reputation: 704

How to construct a query based URL in react

I have an app that takes a search string and returns results in one route : hosts.abc.com:3000. The url doesn't change.

I want the search to be reflected in the url so I can share the link and users don't have to make all selection in the form fields.

eg: hosts.abc.com:3000/?type=all&query=coins

Is it possible to do this using react-router ?

Upvotes: 5

Views: 13552

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

To construct such query you could use native browser URLSearchParams:

const searchParams = new URLSearchParams();
searchParams.append("type", "all");
searchParams.append("query", "coins");
searchParams.toString(); // "type=all&query=coins"

// update browser url
this.props.history.push('/current/route/?' + searchParams.toString());
// or
this.props.history.push({
  pathname: '/current/route/',
  search: searchParams.toString()
})

But if you want better support query-string is a similar option.

Upvotes: 9

Related Questions