Reputation: 5338
I want to use the react router to show a page according to the first part of the URL, because the last part of the URL is holding an ID. How can I read out the last part, now I'm using string.split("/").pop()
URL http://localhost:3003/profile/313a2333
Router
<Routes>
<Route path="/profile" element={<Profile/>} />
</Routes>
Upvotes: 1
Views: 1137
Reputation: 203218
If you don't care about the second path segment and only want to match according to the first segment then use a "*"
wildcard matcher.
<Routes>
<Route path="/profile/*" element={<Profile/>} />
</Routes>
If you do need to capture this second path segment value, then provide a param name for it.
<Routes>
<Route path="/profile/:id" element={<Profile/>} />
</Routes>
Use the useParams
hook to access route path params in the routed components.
const { id } = useParams();
Upvotes: 1
Reputation: 2062
Define your Route
like the following:
<Route path="/profile/:user_id">
Then you can get 2nd parameter in Profile
component.
import { useParams } from 'react-router-dom';
const params: any = useParams();
const user_id = params.user_id;
Upvotes: 2