skip to Main Content

I have it where my header and footer wrap the outlet of my pages but I would like the header and footer to be hidden on certain pages such as the customer and admin dashboard. What would be the best approach for this?

const router = createBrowserRouter(
  createRoutesFromElements(
    // Parent taking in element of entire app
    <Route path='/' element={<App />}>
      <Route index={true} path='/' element={<Home />} />
      <Route index={true} path='/register' element={<Register />} />
      <Route index={true} path='/login' element={<Login />} />
      <Route index={true} path='/logcheck' element={<EnterEmail />} />
      <Route index={true} path='/precheck' element={<Precheck />} />
      <Route index={true} path='/plans' element={<PlansPage />} />

      <Route path='' element={<PrivateRoute />}>
        <Route path='/dashboard' element={<CustomerDash />}/>
      </Route>
    </Route>
  )
)

const root = ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Provider store={store}>
      <RouterProvider router={router} />
    </Provider>
  </React.StrictMode>,
)





function App() {

  return (
    <>
      <Navbar />
      <main>
        <Outlet />
      </main>
      <Footer />
      <ToastContainer />
    </>
  )
}

export default App

2

Answers


  1. you can achieve it by using a wrapper like this :-
    <Route index={true} path=’/’ element={} />

    export const HeaderAllowed = ({ children }) => {
    return (
    <>

    {children}

    </>
    );
    }

    Login or Signup to reply.
  2. There are a lot of ways to do this, but the simplest one is Conditional Rendering. I mean, conditionally rendering the header and footer based on the current route.

    You can use ‘useLocation’ hook to get the current route.

    I assume you don’t want the header and footer on following routes:

    ‘/register’, ‘/login’ and ‘/logcheck’

    Here’s how you can do this.

    import React from 'react';
    import { useLocation } from 'react-router-dom';
    import { Navbar, Footer, ToastContainer } from './components';  // adjust
    
    function App() {
      const location = useLocation();
      const hideHeaderFooter = ['/register', '/login', '/logcheck'].includes(location.pathname);
    
      return (
        <>
          {!hideHeaderFooter && <Navbar />}
          <main>
            <Outlet />
          </main>
          {!hideHeaderFooter && <Footer />}
          <ToastContainer />
        </>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search