Issue
In my project, I saw router v5.2.0 is installed and based on that, routes are defined on where all route are under the switch. I am working on update of react-router
to latest version, so first I am converting all route with CompactRoute
Here is My Current Route:
<Route
path={
'/' +
Constants.USER_ADMIN_TYPE +
'/show-details/:name/:showId'
}
render={(props) => (
<Admin
userType={Constants.USER_ADMIN_TYPE}
comp={
<ShowDetails
{...props}
userType={
Constants.USER_ADMIN_TYPE
}
/>
}
/>
)}
/>
I need help to convert this to latest react-router
syntax.
I had tried, doing like this but its not rendering, and also I am confused, how can I pass the props in new router?
<CompatRoute
path={
'/' +
Constants.USER_ADMIN_TYPE +
'/show-details/:name/:showId'
}
component={
<Admin
userType={Constants.USER_ADMIN_TYPE}
comp={
<ShowDetails
userType={
Constants.USER_ADMIN_TYPE
}
/>
}
/>
}
/>
Solution
Given your react-router-dom@5
route:
<Route
path={'/' + Constants.USER_ADMIN_TYPE + '/show-details/:name/:showId'}
render={(props) => (
<Admin
userType={Constants.USER_ADMIN_TYPE}
comp={
<ShowDetails
{...props}
userType={
Constants.USER_ADMIN_TYPE
}
/>
}
/>
)}
/>
To convert this to the react-router-dom@6
APIs/syntax ensure the following:
- Render all
Route
components within aRoutes
component. TheRoutes
component is the spiritual successor to, and replacement of, the RRDv5Switch
component. TheRoutes
component is what does the heavy lifting of matching the current URL path to a route it manages. - Render all routed content on the
Route
component's singleelement
prop as aReact.ReactNode
, a.k.a. as JSX. - There are no longer "route props", i.e. the RRDv5
history
,location
, andmatch
route props. These are all now accessed via React hooks:location
viauseLocation
,params
viauseParams
, and instead of a history object there is now anavigate
function via theuseNavigate
hook.
The above route converted to RRDv6 route API/syntax:
<Routes>
... other routes ...
<Route
path={`/${Constants.USER_ADMIN_TYPE}/show-details/:name/:showId`}
element={(
<Admin
userType={Constants.USER_ADMIN_TYPE}
comp={<ShowDetails userType={Constants.USER_ADMIN_TYPE} />}
/>
)}
/>
... other routes ...
</Routes>
Answered By - Drew Reese
Answer Checked By - - Candace Johnson (ReactFix Volunteer)