I have a list of routes in react-router v5
const agrRouterConfig = [
{
path: '/',
component: Agreements,
exact: true,
},
{
path: '/agreements/:id',
component: AgreementPdfPage,
},
];
export default agrRouterConfig;
I was passing them via custom route like this, but importantly I have important state to pass as props setShowAgreement :
const RouteWithSubRoutes = (route: any) => {
return (
<Route
path={route.path}
exact={route.exact}
render={(props) => (
<route.component
{...props}
routes={route.routes}
setShowAgreement={route.setShowAgreement}
/>
)}
/>
);
};
And inside the app:
const Routes = () => {
const [showAgreement, setShowAgreement] = useState(false);
///// some code
if (showAgreement) {
return (
<Switch>
{agrRouterConfig.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} setShowAgreement={setShowAgreement} />
))}
</Switch>
);
}
///// some code
);
};
What is important for me is to pass setShowAgreement to route as props. How to achieve that in react-router v6 ? I went through documentation, the approach is pretty different and I can't find a way to translate my code.
Answer.
useRoutes() from react-router v6 accepts arguments for the router[] object.
On my particular example:
// app.tsx
const App = () => {
let element = useRoutes(routerConfig(setShowAgreement));
return <>element </>
}
and inside routerObjc.tsx
//routerObjc.tsx
const routerConfig = (setShowAgreement?: ()=>void ) => [
{
path: '/documents',
element: <Documents setShowAgreemnt={setShowAgreemnt}/>/>
},
{
path: '/profile',
element: <Profile setShowAgreemnt={setShowAgreemnt}/> ,
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.