Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to reference the path parameters in react router dom?

<Route path="users">
  <Route path=":id" element={<UserProfile id={":id"} />} />
</Route>

The above is what I am trying to do. The code isn’t correct. How to make it correct?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The route path params are located on a params object accessible by the useParams hook.

The useParams hook returns an object of key/value pairs of the
dynamic params from the current URL that were matched by the <Route path>. Child routes inherit all params from their parent routes.

For a given route:

<Route path=":id" element={<UserProfile />} />

The UserProfile component will use the useParams hook to access the id route path param.

Example:

import { useParams } from 'react-router-dom';

...

const UserProfile = () => {
  ...

  const { id } = useParams();

  ...

};

If the UserProfile component can’t use React hooks directly for some reason and takes id as a prop, then create a wrapper component to use the hook and inject the prop.

Example:

import { useParams } from 'react-router-dom';

...

const UserProfileWrapper = () => {
  ...

  const { id } = useParams();

  ...

  return <UserProfile id={id} />;
};

<Route path="users">
  <Route path=":id" element={<UserProfileWrapper />} />
</Route>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading