I'd like to hide a component depending on the route with react-router-dom v6. I could make it with exact path, but I'd also like to hide it in nested routes. I tried like this:
{location !== "/dashboard/*" && <Header />}
But it works only on the page http://localhost:3000/dashboard/*, which is not what I want. How could I fix this?
This is the full code:
const location = useLocation().pathname
const conditionLocation = location === "/dashboard" || location === "/dashboard/*"
return !conditionLocation && <Header />
Routes:
// Packages
import React from "react"
import { Routes, Route } from "react-router-dom"
// User
import Dashboard from "../pages/admin/Dashboard"
import EditAccount from "../pages/admin/EditAccount"
function Switch() {
return (
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/dashboard/edit" element={<EditAccount />} />
</Routes>
)
}
export default Switch
Thanks for your help!
CodePudding user response:
Fix this issue using javascript regex:-
{!(location.match(/^\/dashboard.*$/gim)) && <Header />}
Hope that works..
CodePudding user response:
From what I understand, you are wanting to render a Header component only on specific routes. You've not shared much context, but I understand you don't want to render the Header on any "/dashboard" path. You can achieve this with layout and Outlet components.
const HeaderLayout = () => (
<>
<Header />
<Outlet /> // <-- wrapped Route components render into outlet
</>
);
For the routes you want to render with the Header component render them into a route rendering the HeaderLayout.
<Routes>
<Route element={<HeaderLayout />}>
..... routes render into outlet with header
</Route>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/dashboard/edit" element={<EditAccount />} />
</Routes>
