Reputation: 301
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
Upvotes: 2
Views: 1506
Reputation: 202638
Couple of issues:
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