Component not show up in nested router with AuthProvider ,React and Firebase

Viewed 63

I did Authentication with fireBase and a PrivateRoute for the login users. But when I get in one of each other component (not Product login or signup) the URL update but it does not show up. App.js

function App() {
  return (
    <AuthProvider>
        <Switch>
          <PrivateRoute exact path='/' component={MainPageComp}/>
          <Route path='/Signup' component={SignupComp}/>
          <Route path='/Login' component={LoginComp}/>
        </Switch>
      </AuthProvider>
  );
}

In the MainPageComponent there are also Routes:

<Switch>
       <PrivateRoute exact  path='/' component={ProductsComp}/>
       <Route  path='/Products' component={ProductsComp}/>
       <Route  path='/Customers' component={CustomersComp}/>
       <Route  path='/Purchases' component={PurchasesComp}/>
       <Route  path='/AddProduct' component={AddProductComp}/>
       <Route  path='/EditProduct/:id' component={EditProductComp}/>
       <Route  path='/EditCustomer/:id' component={EditCustomerComp}/>
</Switch>

PrivateRoute.js:

export default function PrivateRoute({component:Component,...rest}){

    const {currentUser} = useAuth()
    return(
        <Route
        {...rest}
        render={props=>{
          return currentUser?<Component {...props}/>:<Redirect to='/login'/>
        }}>

        </Route>
    )
}

Thanks for the helpers

1 Answers

Within the Switch component path order and specificity matter! You've incorrectly specified the home "/" path to match exactly. This necessarily precludes any non-exact "sub-routes" from being matched by the PrivateRoute and since the path no longer exactly matches MainPageComp component is unmounted.

To resolve, order routes/paths in the Switch from more specific to less specific paths and remove the exact prop on any paths/routed components that are potentially rendering nested/sub-routes so they can also be matched and rendered. In fact, if specified correctly you should have nearly zero need to ever use the exact prop.

App

function App() {
  return (
    <AuthProvider>
      <Switch>
        <Route path='/Signup' component={SignupComp}/>
        <Route path='/Login' component={LoginComp}/>
        <PrivateRoute path='/' component={MainPageComp}/>
      </Switch>
    </AuthProvider>
  );
}

MainPageComp

<Switch>
  <Route  path='/Products' component={ProductsComp}/>
  <Route  path='/Customers' component={CustomersComp}/>
  <Route  path='/Purchases' component={PurchasesComp}/>
  <Route  path='/AddProduct' component={AddProductComp}/>
  <Route  path='/EditProduct/:id' component={EditProductComp}/>
  <Route  path='/EditCustomer/:id' component={EditCustomerComp}/>
  <PrivateRoute path='/' component={ProductsComp}/>
</Switch>
Related