Home > Enterprise >  useParams() is an empty object in react-router-dom v6.8
useParams() is an empty object in react-router-dom v6.8

Time:02-01

I am simply trying to retrieve the params from a dynamic route ("/articles/:articleId") in React using react-router-dom v 6.8

"react-router-dom": "^6.8.0",    
"@types/react-router-dom": "^5.3.3",

I tried to follow unexpected Output

CodePudding user response:

Couple of issues:

  1. You are directly calling the React functions instead of rendering them as JSX. The components aren't called as part of the normal React component lifecycle, so the params are not populated.
  2. react-router-dom@6 is written entirely in Typescript, so there is no need for any external typings, especially those from react-router-dom@5 which will be woefully incorrect for RRDv6.

The Route component's element prop takes a React.ReactNode, a.k.a. JSX, value.

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/articles/:articleId" element={<Article />} />
        <Route path="/articles" element={<Articles />} />
        <Route path="/404" element={<NotFoundPage />} />
        <Route path="/" element={<HomePage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </Router>
  );
}

Uninstall the unnecessary dependency.

npm uninstall --save @types/react-router-dom
  • Related