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 (
// ...
);
}
Edit:
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>
}
/>