5

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 ?

1
  • It is possible, what do you have problem with? Commented May 6, 2018 at 7:15

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is much harder than i thought. the history.push does add it to the url, But when I visit the url ,say, hosts.abc.com:3000/?type=all&query=coins Its just showing the base page hosts.abc.com:3000/ . How can i perform call the search function?
Also, I want /home and /home/:query in my routes file, This is leading to same content being displayed twice
had to use componentDidMount method to parse parameters and us an if condition to not set if the query is already present in url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.