This is what I have:
//index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
import AdminLayout from "layouts/Admin.js";
import AuthLayout from "layouts/Auth.js";
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path="/admin" render={(props) => <AdminLayout {...props} />} />
<Route path="/auth" render={(props) => <AuthLayout {...props} />} />
<Redirect from="/" to="/admin/index" />
</Switch>
</BrowserRouter>,
document.getElementById("root")
);
As you can see, you can go both to all the pages under "admin" and "auth" without any auth check. The files under the folder "layouts/" have both an:
import routes from "routes.js";
And (a part from layout data) respectively:
<Switch>
{getRoutes(routes)}
<Redirect from="*" to="/admin/index" />
</Switch>
and
<Switch>
{getRoutes(routes)}
<Redirect from="*" to="/auth/login" />
</Switch>
The router.js contains this:
import Index from "views/Index.js";
import Login from "views/examples/Login.js";
import Tables from "views/examples/Tables.js";
const routes = [
{
path: "/index",
name: "Dashboard",
icon: "ni ni-tv-2 text-primary",
component: Index,
layout: "/admin",
},
{
path: "/tables",
name: "Tables",
icon: "ni ni-bullet-list-67 text-red",
component: Tables,
layout: "/admin",
},
{
path: "/login",
name: "Login",
icon: "ni ni-key-25 text-info",
component: Login,
layout: "/auth",
},
];
export default routes;
To add authentication I followed this guide:
https://www.nicknish.co/blog/react-router-authenticated-routes
So I added this in index.js:
export const fakeAuth = {
signedIn: false
};
const RequireAuth = ({ children }) => {
if (!fakeAuth.signedIn) {
return <Redirect to="/auth/login" />;
}
return children;
};
However, what it happens it that, no matter what url I go to, I will always be redirected to this:
http://localhost:3003/auth/login
And the problem is that the page is completely empty with no errors in the console. The login-page is not rendered for some reason. And it does not look as I went inside an infinite loop.