Auth0 Blog React Auth guide assistance

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:

  1. Why is the ProtectedRoute component behaving differently from when withAuthenticationRequired is at the export level?
  2. Do I need to protect routes that are nested within a protected route?

Thanks for any help!

Hey there @grant-nations, welcome to the Auth0 Community!

I pulled your question from the parent topic on this front so it can get additional help since it’s expanded from the original Blog post: The Complete Guide to React Authentication with Auth0

I will work to see if I can find a solution to your questions above and let you know as details roll in. Thanks :slightly_smiling_face:

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.