How To Get Url Params in React
By Henri Parviainen
Getting access to url params may be crucial to make your application work as intended. In this post, we will explain several ways how you can get access to url params (also known as query params) in React apps.
Let's say we have the following url, and we want access to the post
param value.
https://www.webdevolution.com/blog?post=123
Using the Browser API and Window Object
One way to get url param value in React would be by using the browser API and its window
object.
const params = new URLSearchParams(window.location.search);
const paramValue = params.get("post");
// paramValue == 123
Before using this approach, regard that URLSearchParams
is not supported by IE.
If you need to support IE, use the approach explained below.
Using React Router
If you are using React Router, you can use the React router's location
object to get your current location instead of window.location
.
You can get access to it in any component that inherits from Route
by simply getting it from the props.
props.location.search;
There are two solutions to parse the url param value out of the location object's search
field.
1. With query-string
library (if there is a need for IE Support)
First, you will have to install the query string library.
npm install query-string
Then you can use it to parse the search
field like this.
import * as queryString from "query-string";
let params = queryString.parse(props.location.search);
// params == {'post': 123}
2. With the URLSearchParams
API (if no need for IE support)
If you are using react-router and don't care to support IE you can also parse the location object search field with the URLSearchParams
API just as we did it before.
let paramValue = new URLSearchParams(props.location.search).get("post");
// paramValue == 123
Conclusion
Here we explained three different solutions to get url params in React apps. There are other solutions as well, but these are three simple working solutions that I prefer.