'Context-provider on specific routes inside <Switch>
Using a <Switch> helped me refer wrong addresses to the start page and also deal with user-access-restrictions (to certain pages).
But I can't seem to use the Context-providers to their specific routes any longer.
The problem is that I don't want the Context-providers to wrap around ALL routes/components.
// App.js
<Router>
<RoleInfoProvider>
<AccessWrapper>
<NavBar />
<TimesheetProvider>
<Switch>
<PrivateRoute exact path="/approvals"component={Approvals} />
<PrivateRoute exact path="/reports" component={Reports} />
<Route exact path="/timesheet" component={Timesheet} />
<Route component={Start} />
</Switch>
</TimesheetProvider>
</AccessWrapper>
</RoleInfoProvider>
</Router>
While actually, I would've prefered to have <TimesheetProvider> wrap around only like this:
<Switch>
<PrivateRoute exact path="/approvals"component={Approvals} />
<TimesheetProvider>
<PrivateRoute exact path="/reports" component={Reports} />
<Route exact path="/timesheet" component={Timesheet} />
</TimesheetProvider>
<Route component={Start} />
</Switch>
What happens when I visit /timesheet/ is both Reports and Timesheet are rendered.
I realise this might be a problem with my ProtectedRoute so I'll show you that component too.
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import useRoleInfo from '../hooks/useRoleInfo';
function ProtectedRoute({ path, ...rest }) {
const { roleInfo } = useRoleInfo();
if (
(path === '/approvals' && roleInfo.canAccessApprovals) ||
(path === '/reports' && roleInfo.canAccessReports)
) {
return <Route {...rest} />;
}
return <Redirect to="/" />;
}
export default ProtectedRoute;
Any idea of how the use of Context-providers and Router-Switch could work better?
Solution 1:[1]
It might be a little late, but it might help others in the future:
If you want only to separate the context and, having it exclusive for certain routes, you have to create another switch and separate each Routes that share same context, like this:
<Router>
<RoleInfoProvider>
<AccessWrapper>
<NavBar />
<Switch>
<TimesheetProvider>
<PrivateRoute exact path="/reports" component={Reports} />
<Route exact path="/timesheet" component={Timesheet} />
</TimesheetProvider>
</Switch>
<Switch>
<PrivateRoute exact path="/approvals"component={Approvals} />
<Route component={Start} />
</Switch>
</AccessWrapper>
</RoleInfoProvider>
</Router>
For some reason, when you use a unique Switch and place the context provider directly inside of it, the rest of routes won't be working, apearing, executing or something like that. Maybe due context collisions, since Route was already rendered with some context and suddendly we add another one, react throws an error without calling an error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roberto Lucas |
