Each of your layout should have a path component to differentiate from other layouts.
For example
Auth layouts could reside under /auth
eg, login would /auth/login
, signup would be /auth/signup
App layout could go under /app
eg, dashboard would be /app/dashboard
, home would be /app/home
Working Demo
App.js
import { Switch, BrowserRouter, Route, Redirect } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<Layouts />
</BrowserRouter>
);
}
Layouts.js
const NotFound = () => <h1>Not Found</h1>;
function Layouts() {
return (
<Switch>
<Route path="/auth" component={AuthLayout} />
<Route path="/app" component={AppLayout} />
<Route path="/" component={NotFound} />
</Switch>
);
}
AuthLayout
const Signup = () => <p>Login</p>;
const Login = () => <p>Sign up</p>;
function AuthLayout() {
return (
<div>
<h1>Auth Layout</h1>
<Route path="/auth/signup" exact component={Signup} />
<Route path="/auth/login" exact component={Login} />
<Redirect from="/auth" to="/auth/login" exact />
</div>
);
}
AppLayout
const Home = () => <p>Home</p>;
const Dashboard = () => <p>Dashboard</p>;
function AppLayout() {
return (
<div>
<h1>App Layout</h1>
<Route path="/app/home" exact component={Home} />
<Route path="/app/dashboard" exact component={Dashboard} />
<Redirect from="/app" to="/app/home" exact />
</div>
);
}
Also if you want to protect certain routes from being rendered if not authenticated, then you can create a PrivateRoute
component that would redirect to auth layout if not authenticated.
PrivateRoute.js
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props => sessionStorage.token // your auth mechanism goes here
? <Component {...props} />
: <Redirect to={{ pathname: '/auth' }} />}
/>
);
You can use this PrivateRoute
component instead of react-router
's Route
component.
Eg:
<PrivateRoute path="/app" component={AppLayout} />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…