[The easy way to] get url params in React without react-router


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)

Additional Resources

Recent Posts

link to How to fix: Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

How to fix: Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

This common Javascript error, “Element type is invalid,” is usually caused by a mismatch between import and exports. You are trying to import the default export from a module that only exports...