How can I conditionally return different navbars/headers in app.js based on the route?

Viewed 26

I couldn't find any clear answers on this so I thought I'd ask. I am trying to render 2 different headers for two different routes. So ideally, if we're on the '/home', we return my decked out <HeaderHome />, and if we are in '/projects' route, then render a more simple header in <HeaderProjects />. Below is my code structure.

function App() {
  return (
    <>
      <div className={styles.container}>
        <main className={styles.main}>
          {(path == "/home") ? <HeaderHome /> : <HeaderProjects />}   
          <Routes>
              <Route path="/home" element={< Home />} />
              {/* <Route path="/about" element={< About />} />
              <Route path="/resume" element={<Resume />} /> */}
              <Route path="/projects" element={<Projects />} />           
              {/* <Route path="/contact" element={<Contact />} />     */}
          </Routes>
          <Footer /> 
        </main>
      </div>
    </>
  )
}

Thank you for taking a look.

1 Answers

You can use layout components that render the specific header component you want and an Outlet for nested routes.

Example:

import { Outlet } from 'react-router-dom';

const HomeLayout = () => (
  <>
    <HeaderHome />
    <Outlet />
  </>
);

const ProjectsLayout = () => (
  <>
    <HeaderProjects />
    <Outlet />
  </>
);

function App() {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <Routes>
          <Route element={<HomeLayout />}>
            <Route path="/home" element={<Home />} />
          </Route>

          <Route element={<ProjectsLayout />}>
            <Route path="/projects" element={<Projects />} /> 
          </Route>

          <Route path="/about" element={<About />} />
          <Route path="/resume" element={<Resume />} />          
          <Route path="/contact" element={<Contact />} />
        </Routes>
        <Footer /> 
      </main>
    </div>
  );
}
Related