I'm using React-Router-DOM v6.19.0 in my React app. I have a Layout
for the routes in Root.jsx:
function Root() {
return (
<>
<Header />
<Outlet />
<Footer />
</>
)
}
export default Root
This is being shown in my main routes in Main.jsx:
const router = createBrowserRouter(
createRoutesFromElements(
<Route path='/' element={<Root />}>
<Route path='' element={<Home />}/>
<Route path='about' element={<About />}/>
<Route path='pinboard' element={<Todos />}/>
<Route path='lists' element={<Lists />}/>
</Route>
)
)
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
)
As you can see, the header and footer are being rendered in each route, with only the Outlet
changing.
The problem is, I don't want to display the header and footer on a specific route (like the sign-up page).
How can I achieve this?
I tried to make a condition check:
const location = useLocation();
const DontRenderHeaderFooter = ['/login', '/signup'];
const renderHeaderFooter = !DontRenderHeaderFooter.includes(location.pathname);
return (
<>
{renderHeaderFooter && <Header />}
<Outlet />
{renderHeaderFooter && <Header />}
</>
)
But that didn't seem to work.
You could add a <Wrapper />
component that will wrap some component in the Header + Footer.
So in this example we Wrap every component in the Header + Footer, except the <Home />
component, that will just render itself. (The login route you mention in the question)
const router = createBrowserRouter(
createRoutesFromElements(
<Route path='/' element={<Wrapper><Home /></Wrapper>}>
<Route path='' element={<Home />}/>
<Route path='pinboard' element={<Wrapper><Todos /></Wrapper>}/>
<Route path='lists' element={<Wrapper><Lists /></Wrapper>}/>
</Route>
)
)
const Wrapper = (props) => (
<React.Fragment>
<Header />
{props.children}
<Footer />
<React.Fragment>
)