Search code examples
javascriptreactjsreact-routerreact-router-dom

React - get parameters from route path in another component


I tried to find it, but I couldn't do it. I tested many results but the effects were disappointing.

So I have this structure of application:

<BrowserRouter>
  <Menu/>
  <Routes>
    <Route path="/business/:id" element={<SomePage />} />
  </Routes>
</BrowserRouter>

In SomePage component I can use useParams and I see this id like object { id: 6 } - it's fine and makes sense. But I have a case when I have to extract this id in Menu component and useParams returns:

{
  *: "business/6"
}

But I would like to get object:

{
  id: 6
}

I tried to use matchPath, useMatch, useResolvedPath, and others but I didn't have any special effects.


Solution

  • If you are rendering Menu outside a Routes component then use the useMatch hook to check if there is a match for the "/business/:id" path. If there is a match then useMatch returns a Match object that has a params property, otherwise it returns null (so use a guard-clause or null-check before accessing into the return value).

    You could alternatively create a layout route component that renders Menu along with an Outlet and render it within the Routes component and use the useParams hook to access the params object.

    Example:

    import { Routes, Route, Outlet, useParams, useMatch } from "react-router-dom";
    
    const MenuStandalone = () => {
      const match = useMatch("/business/:id");
    
      console.log("MenuStandalone", match?.params);
    
      return (
        <>
          <h1>MenuStandalone</h1>
          <Outlet />
        </>
      );
    };
    
    const MenuLayout = () => {
      const params = useParams();
    
      console.log("MenuLayout", params);
    
      return (
        <>
          <h1>MenuLayout</h1>
          <Outlet />
        </>
      );
    };
    
    const SomePage = () => {
      const params = useParams();
    
      console.log("SomePage", params);
    
      return <h1>SomePage</h1>;
    };
    
    export default function App() {
      return (
        <div className="App">
          <MenuStandalone />
    
          <Routes>
            <Route element={<MenuLayout />}>
              <Route path="/business/:id" element={<SomePage />} />
            </Route>
          </Routes>
        </div>
      );
    }
    

    Edit react-get-parameters-from-route-path-in-another-component

    enter image description here