skip to Main Content

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

2

Answers


  1. 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();
      // ...
    }
    
    Login or Signup to reply.
  2. 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"
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search