React Router is a great tool for handling routing in React apps. But, if you aren’t building a full single-page app (SPA) react-router is probably overkill. If you just want to get access to url parameters there is an easy way to do it without react-router.
The easiest way to get url parameters in Javascript and React is to use the window.location.search object and built-in module URLSearchParams. This should work in all modern browsers.
URLSearchParams parses a URL query string and creates an object you can use to access each of the url parameters in the url.
// on page http://mysite.com/hello.html?message=world&type=text
var sp = new URLSearchParams(window.location.search)
sp.get('message') // world
sp.get('type') // text
Code language: JavaScript (javascript)
Updating url parameters
URLSearchParams can also be used to update the url params, which will cause the browser to load the new url. This is similar to updating window.location.href to redirect the browser to a new page.
// on page http://mysite.com/hello.html?message=world&type=text
var sp = new URLSearchParams(window.location.search)
sp.set('type', 'something')
window.location.search = sp.toString()
// browser loads http://mysite.com/hello.html?message=world&type=something
Code language: JavaScript (javascript)