Omar Trkzi
Omar Trkzi

Reputation: 301

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

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

Upvotes: 2

Views: 1506

Answers (1)

Drew Reese
Drew Reese

Reputation: 202638

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

Upvotes: 1

Related Questions