<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?
CodePudding user response:
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>