'useParams() unable to fetch path dynamically react-router v6
My code is unable to render the elements of the nested route component present in my QuoteDetail code block while I'm using the dynamic path value
import { Route, Routes, Navigate } from "react-router-dom";
import AllQuotes from './pages/AllQuotes';
import QuoteDetail from './pages/QuoteDetail';
function App() {
return (
<div>
<Routes>
<Route path='/' element={<Navigate to='/quotes' />} />
<Route path='/quotes' element={<AllQuotes />} />
<Route path='/quotes/*' element={<QuoteDetail />} />
<Route path='/quotes/:quoteId' element={<QuoteDetail />} />
</Routes>
</div>
);
}
export default App;
this is my Quote details code
import { Fragment } from "react";
import { useParams } from "react-router";
import { Routes, Route } from "react-router-dom";
import Comments from "../components/comments/Comments";
const QuoteDetail = () => {
const params = useParams();
console.log(params.quoteId);
return (
<Fragment>
<h1>Quote Detail Page</h1>
<p>{params.quoteId}</p>
<Routes>
<Route
path={`${params.quoteId}/comments`}
element={<p>Hello</p>}
/>
</Routes>
</Fragment>
);
};
export default QuoteDetail;
Solution 1:[1]
If QuoteDetail
is rendering sub-routes then specify the *
wildcard at the end of of the "quoteId" route to allow further/more deeply matching.
function App() {
return (
<div>
<Routes>
<Route path='/' element={<Navigate to='/quotes' />} />
<Route path='/quotes' element={<AllQuotes />} />
<Route path='/quotes/:quoteId/*' element={<QuoteDetail />} />
</Routes>
</div>
);
}
You can also use relative matching/linking from the QuoteDetail
, it's actually not necessary to know the current quoteId
to create links to, and match, further sub-routes. You can just specify the relative path from the current location. Paths starting with "/"
are absolute, and without are relative.
const QuoteDetail = () => {
const params = useParams();
return (
<Fragment>
<h1>Quote Detail Page</h1>
<p>{params.quoteId}</p>
<Routes>
<Route
path="comments"
element={<p>Hello</p>}
/>
</Routes>
</Fragment>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Drew Reese |