I am having an issue with the ProtectedRoute component that doesn’t exist if I use withAuthenticationRequired directly in the export statement of the component that I am trying to protect. I have a web app that contains routes like the following:
<Router> {isAuthenticated && <Header />} <Switch> <Route exact path='/'> {isAuthenticated ? <Redirect to="/home" /> : <LandingPage />} </Route> <ProtectedRoute path='/home' component={Home}/> <ProtectedRoute path='/events' component={Events}/> <ProtectedRoute path='/dates' component={Dates}/> </Switch> </Router>
And my Home component contains something like the following:
function Home(){ return <div className="home-page"> <Sidebar /> <ProtectedRoute path={"/home/dogs"} component={Dogs}/> <ProtectedRoute path={"/home/cats"} component={Cats}/> </div> } export default Home;
The bug also happens when the Home component doesn’t use ProtectedRoute like so:
function Home(){ return <div className="home-page"> <Sidebar /> <Route path={"/home/dogs"} component={Dogs}/> <Route path={"/home/cats"} component={Cats}/> </div> } export default Home;
This creates an error that I can’t really explain, but it prevents the state within the Sidebar component from changing the sidebar’s appearance and rendered components.
Here is a link to a codesandbox on how the sidebar should work (no auth0).
When using ProtectedRoute as in the code above, the active class on the navbar links changes, but the rest of the content stays the same.
However, if I instead take the ProtectedRoute off of the Home component, but use withAuthenticationRequired on the export of the Home component, like so:
export default withAuthenticationRequired(Home, { onRedirecting: () => (<div>Redirecting you to the login page...</div>) });
and
<Route path='/home' component={Home}/> //instead of ProtectedRoute
Then everything works as it should.
My questions are:
- Why is the ProtectedRoute component behaving differently from when withAuthenticationRequired is at the export level?
- Do I need to protect routes that are nested within a protected route?
Thanks for any help!