2

Originally this is how the route looks like in App.js:

App.js

<Route
  path="/home"
  name="Home"
  render={props => <DefaultLayout {...props} />
/>

DefaultLayout.js

<Switch>
  {routes.map((route, idx) => {
    return route.component ? (
      <Route
        key={idx}
        path={route.path}
        exact={route.exact}
        name={route.name}
        render={props => <route.component {...props} />}
      />
    ) : null;
  })}
  <Redirect from="/home" to="/home/dashboard" />
</Switch> 

So basically, the /home route directs to DefaultLayout component which contains all the nested routes of the app. This works perfectly.
Since, only the authenticated user should have access to the home page, I have implemented a PrivateRoute component :

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);

App.js

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

Now, I get a blank screen after logging-in. (Although I do get redirected to /home/dashboard). So the internal routing of the DefaultLayout component, doesn't work like properly anymore.
REMARK: I've found-out that the nested-routes inside DefaultLayout component have to be defined inside App.js for them to work. For example:

DefaultLayout.js

 <Redirect from="/home" to="/home/dashboard" />

App.js

<PrivateRoute
  exact
  name="Dashboard"
  path="/home/dashboard"
  component={Dashboard}
/> 

But, I can't do this for all routes. The strange thing is that before using PrivateRoute, the nested routes worked perfectly. And I don't understand why the PrivateRoute component made the nested-routing inside DashboardLayout not function properly?

AG_HIHI
  • 1,705
  • 5
  • 27
  • 69

0 Answers0