I have upgraded to react-router-dom v6 I have been using RouteComponentProps for mapping over routes as below but was wondering how to inplement this in v6
<Switch>
{routes.map((route, index) => {
return (
<Route
key={index}
exact={route.exact}
path={route.path}
render={(routeProps: RouteComponentProps<any>) => (
<route.component {...routeProps} />
)}
/>
);
})}
</Switch>
I know that Switch is now replaced with Routes, but tnot sure what replaces RouteComponentProps
CodePudding user response:
Version 6 does not have Switch
and has removed the render
function too.
Instead of Switch
, use Routes
.
Intead of the render
method, use element
which is a React.ReactNode
.
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="messages" element={<DashboardMessages />} />
<Route path="tasks" element={<DashboardTasks />} />
<Route path="about" element={<AboutPage />} />
</Routes>;
Only if <route.component />
is a React.ReacNode
.
<Routes>
{routes.map((route, index) => {
return (
<Route key={index} path={route.path} element={<route.component />} />
);
})}
</Routes>;
Reference:
https://reactrouter.com/docs/en/v6/components/route
CodePudding user response:
There is no replacement for the route props in react-router-dom@6
. Components should instead use the React hooks:
Note that there are several other new hooks in RRDv6.
Code:
<Routes>
{routes.map((route) => {
const Component: React.ReactNode | null = route.component;
return (
<Route
key={route.path}
path={route.path}
element={<Component />}
/>
);
})}
</Routes>
If the route component is still a class component then you'll need to either convert them to function component or create your own custom withRouter
HOC since that was also removed in v6.
Example:
const withRouter = Component => props => {
const location = useLocation();
const params = useParams();
const navigate = useNavigate();
return <Component {...props} {...{ location, params, navigate }} />;
};