score:3

Accepted answer

issue

the route's path prop only specifies route params, not query string parameters.

for example, for path="/root/:id" if a user were to navigate to "/root/test", then inside a component you could access the route params from the match object. something like the following:

const { id } = props.match;
console.log(id); // "test"

even if a user navigated to "/root/test?qp1=hello&qp2=world" the route params would still only pick up id from the path.

you also can't assign the same match param to multiple path segments. path="/salesoff/:id/salesdist/:id/custname/:id/product/:id/productgroup/:id" can't/shouldn't all assign to match.params.id.

solution

you can, however, get the entire query string from the location object, and in this case it is the whole query string as a single string. given the same path from before, "/root/test?qp1=hello&qp2=world", then you can access the query string as follows:

const { search } = uselocation();
console.log(search); // "?qp1=hello&qp2=world"

it's up to you to now parse the query string if you want to access specific key-value pairs.

const { search } = uselocation();
const urlparams = object.fromentries([...new urlsearchparams(search)]);
console.log(urlparams); // { qp1: 'hello', qp2: 'world' }

demo

demo with your code and url "/?salesoff=s4&salesdist=district%201&custname=c2&product=p2&productgroup=pg-1"

edit extract-value-from-url-using-react-router


Related Query

More Query from same tag