1

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>
2

2 Answers 2

2

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;

Sign up to request clarification or add additional context in comments.

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.