Reputation: 405
How can I hide Topbar on Login and Register pages? I'm trying to show the Topbar on all pages but hide it on Login and Register pages
The Code
return (
<Router>
<TopBar/>
<Routes>
<Route path="/register" element={user ? <Home /> : <Register />} >
</Route>
<Route path="/login" element={user ? <Home /> : <Login />}>
</Route>
<Route path="/settings" element={user ? <Settings /> : <Register />}>
</Route>
</Routes>
</Router>
);
Upvotes: 1
Views: 321
Reputation: 1467
You cloud try something like this
{window.location.pathname != "/Login" &&
window.location.pathname != "/Register" && <Topbar />}
window.location.pathname //returns the current url minus the domain name
Or since your using user object to detect whether the current user is login or not why not use it in your logic as well .
{user && <Topbar />}
Upvotes: 1
Reputation: 7801
You can return null
inside the components you want to hide when the path matches /login
or /register
using useLocation()
hook:
const TopBar = () => {
const { pathname } = useLocation();
if (pathname === "/login" || pathname === "/register") return null;
return (
// ...
);
}
When you are on your <Home>
component, the <TopBar>
will not appear because you conditionally render it on the excluded routes. You can solve this problem by removing the conditions in your routes and moving them in your components instead. It means that each route will always renders the same component (or redirect to another route).
First, you can remove the conditions in your three routes and add a /home
route:
<Route path="/home" element={<Home />} />
And then on the components that need a redirection, you can use React Router's <Navigate>
:
const Login = () => {
// If you can't access `user` here you can pass it as a prop
if (user) return <Navigate to="/home" />
return (
// ...
);
}
Since all your routes depend on user
, if you don't want to put a <Navigate>
on every components you can create a helper component to deal with it:
const WithRedirect = ({ to, children }) => (
if (user) return <Navigate to={to} />
return children;
};
And then:
<Route
path="/login"
element={
<WithRedirect to="/home">
<Login />
</WithRedirect>
}
/>
Upvotes: 3