The contents are as follows.
<Route path="/:id" >
<Navigate
to="/intro?Id=:id"
/>
</Route>
Is there a way to pass the :id parameter to the Route tag as the :id parameter to the Navigate tag like this?
The contents are as follows.
<Route path="/:id" >
<Navigate
to="/intro?Id=:id"
/>
</Route>
Is there a way to pass the :id parameter to the Route tag as the :id parameter to the Navigate tag like this?
OK, I see, so you want to render essentially a redirect from "/:id" to "intro?Id=:id".
You can't just redirect from one path to the other since you are dynamically using the id route match param as part of a querystring parameter, and since react-router-dom doesn't deal with the URL querystring you need to handle this mapping yourself. It took a bit of digging through the version 6 docs but this is what I've come up with:
Create a custom component to read the match param and render the Navigate component.
const IntroRedirect = () => {
const { id } = useParams();
return <Navigate replace to={`/intro?Id=${id}`} />
};
Render MyNavigate on a Route.
<Route path="/:id" element={<IntroRedirect />} />
Full demo code:
import {
BrowserRouter as Router,
Link,
Routes,
Route,
Navigate,
useLocation,
useParams
} from "react-router-dom";
const IntroRedirect = () => {
const { id } = useParams();
return <Navigate replace to={`/intro?Id=${id}`} />;
};
const Intro = () => {
const { search } = useLocation();
const query = new URLSearchParams(search);
const Id = query.get("Id");
return <div>Intro: Id="{Id}"</div>;
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Router>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/1234">"/1234"</Link>
</li>
<li>
<Link to="/4567">"/4567"</Link>
</li>
<li>
<Link to="/7890">"/7890"</Link>
</li>
</ul>
<Routes>
<Route path="/intro" element={<Intro />} />
<Route path="/:id" element={<IntroRedirect />} />
</Routes>
</Router>
</div>
);
}