Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 the Docs, but I must be missing something here.

App.tsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
}

Article.tsx

import { useParams } from "react-router-dom";
import { useEffect } from "react";

const Article = () => {
  const { articleId } = useParams()
  const params = useParams()

  useEffect(() => {
    console.log('even inside useEffect', params);
  }, [])
    
  console.log("Article  ", useParams(), articleId)

  return (
    <div>ID: {articleId}</div>
  )
}

export default Article

Output
unexpected Output

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading