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?