0

I have a react application where I wanted to render some menus depending upon the path.

I have following URL :

http://localhost:3000/Test/marks

Now from this URL I need to get the Test string only so that I can match that string with the array and then get the associated objects with that key.

I tried using the useLocation but it gives us the object and again I have to add a regex to get that name.

Is there any other way ?
Thanks

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
ganesh kaspate
  • 1
  • 9
  • 41
  • 88
  • Have you try [that](https://stackoverflow.com/questions/47693540/get-an-active-route-with-react-router-in-reactjs) – Hakimov-dev Jun 19 '23 at 07:05

2 Answers2

0

You can achive this using useParams hook

<Route path='/:id/marks' element={<Component/>}>

in Your component

import { useParams } from 'react-router-dom';

function Component() {
  // Get the id param from the URL.
  let { id } = useParams();
  // ...
}
Yuvaraj M
  • 933
  • 1
  • 4
  • 11
0

You mention the useLocation hook so I'll assume you are using react-router or react-router-dom. You can use the useMatch hook to test a path pattern, and if there is a match a match object is returned. The match object has a params property that will have any path params available on it.

declare function useMatch<
  ParamKey extends ParamParseKey<Path>,
  Path extends string
>(
  pattern: PathPattern<Path> | Path
): PathMatch<ParamKey> | null;
interface PathMatch<ParamKey extends string = string> {
  params: Params<ParamKey>;
  pathname: string;
  pattern: PathPattern;
}

Example:

Test path: "/Test/marks"

import { useMatch } from 'react-router-dom';

...

const match = useMatch("/:key/marks");
console.log(match?.params?.key); // "Test"
...

If the component that needs to access that part of the URL path is already rendered as part of the normal routing, e.g. on a route rendered on path "/:key/marks", it could also just use the useParams hook directly to access the key path parameter.

Example:

<Route path="/:key/marks" element={.....} />

And in the route component on test path: "/Test/marks"

const { key } = useParams(); // "Test"
Drew Reese
  • 165,259
  • 14
  • 153
  • 181