Can’t Able To Access Params From The URL? Check This…

Arun Kashyap
2 min readOct 7, 2021

A Simple Program That Will Save Your Precious Time!

Photo by Remotar Jobs on Unsplash

Most of the websites use sending params into the URL(eg. item key or token). So we check how we can access params.

Routing

<Router>
<Switch>
<Route path="/users/:key" component={ComponentName} />
</Switch>
</Router>

Sending Params In URL

let suppose you have a listing of some users and where each user have unique key that represents their individuality. All you need to write below code on onClick of that item which will navigate you with key and you can see your key on URL.

history.push("/users/&key=" + key ); // where key is item id you click on// you can send as much as params you wanna send.

Accessing Params

Now, you have two ways to get these params from the url :

useLocation

Now you can just do in simple steps :

import { useLocation } from "react-router-dom";const useQuery = () => {
return new URLSearchParams(useLocation().search);
};
const query = useQuery();
const token = query.get("key");

JS Function

And this is another approach with function :

getUrlVars = () => {
var vars = [],
hash;
var hashes = window.location.href
.slice(window.location.href.indexOf("?") + 1)
.split("&");
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split("=");
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
};

and when you want to use value then call :

let queryParms = getUrlVars();=> queryparams["key"]

Let me know if this works for you. Happy Coding :)

--

--

Arun Kashyap

Experienced Learning Specialist with a demonstrated history of working in the computer software industry. Skilled in ReactJS, Hooks, Redux, Firebase.