1

I am following this tutorial to implement Nested routing.
Here's the relevant code:

App.js

   <PrivateRoute
                exact
                name="Home"
                path="/home"
                component={DefaultLayout}
              />  

DefaultLayout.js

const Users = React.lazy(() => import("../../views/Users/Users"));

          <Route path="/home/users" component={Users} />

PrivateRoute.js

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      auth.isAuthenticated === true ? (
        <Component {...props} />
      ) : (
        <Redirect to="/" />
      )
    }
  />
);

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);

So as you may have guessed, I am protecting the /home route with the PrivateRoute component.
The /home routes is associated with DefaultLayout component.
The DefaultLayout component contains a NestedRoute that is /home/users which leads to the component Users.

The private route functions properly and it routes the user after he logs-in to the default layout:
enter image description here
However when I click on a button that routes me to /home/users, I get this blank screen:
enter image description here Any idea what I've done wrong?
EDIT 1: When I add this to App.js:

   const Users = React.lazy(() => import("../../views/Users/Users"));

              <Route path="/home/users" component={Users} />

I do get routed to the Users component. However, not as a nested route but as a component in the root routes. In other words, the Users component does not appear inside the defaultLayout component but appears as a root component. I hope that makes sense. Here's a screenshot:
enter image description here

EDIT 1 Conclusion: The Nested routing implementation doesn't work. The app still routes from inside App.js instead from inside DefaultLayout.js.
EDIT 2: I realized that even without the PrivateRoute component and using the normal Route component, the nested routing still doesn't work:

      <Route exact path="/home" name="Home" component={DefaultLayout} />
AG_HIHI
  • 1,705
  • 5
  • 27
  • 69

1 Answers1

0

Looks like you need to remove the exact prop from your Home Route:

<Route path="/home" name="Home" component={DefaultLayout} />

With exact, your DefaultLayout component will only be rendered when the url is exactly /home. Since /home/users isn't equal to /home, when you navigate to /home/users, neither your DefaultLayout component nor the nested Users route will be rendered.

Here are the docs that describe the exact prop: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Route.md#exact-bool

Matt Read
  • 33
  • 6