I'm trying to build up private and public routes for my react website.
I have a problem: when I try to go directly with the link with the path name, it'll redirect to the home page.
For example, I have a private route with a path name dashboard
when direct enter the link: https://localhost:3000/dashboard
will still redirect to https://localhost:3000/
.
I'm guessing it is because of the PrivateRoutes() function, which will always redirect the path to the home page but not sure how to modify it.
App.js
const App = () => {
const {
state: { isAuthenticated },
} = AuthContext();
function PrivateRoutes() {
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
}
function PublicRoutes() {
return isAuthenticated ? <Navigate to="/home" /> : <Outlet />;
}
return (
<BrowserRouter>
<Routes>
<Route element={<PrivateRoutes />}>
<Route path="/*" element={<Layout />} />
</Route>
<Route path="*" element={<Error />} />
<Route path="login" element={<PublicRoutes />}>
<Route path="/login" element={<Login />} />
</Route>
</Routes>
</BrowserRouter>
);
};
Layout.js
const Layout = () => {
return (
<Box>
<Header />
<Routes>
<Route index element={<Home />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="transaction" element={<Transaction />} />
<Route path='/*' element={<Navigate to="/" />} />
</Routes>
<Footer />
</Box>
);
};