Search code examples
reactjsreact-routerreact-router-dom

How to use two navbar in react on two different pages


<>  
  <Header />
  <Routes>      
    <Route path='/' element={<Home />} />
    <Route path='application' element={<Application />} />
    <Route path='services' element={<Services />} />
    <Route path='subscription' element={<Subscription />} />
    <Route path='complain' element={<Complain />} />
  </Routes>
  <Footer />
</>

I have created two headers (header, header1) I want to use header1 just on complain page and except complain page I want to use header but I don't know how to use it.


Solution

  • You can use conditionally rendering. And use useLocation from react-router-dom. So base on the comp that are showing that certain header is showing aswell.

    import { useLocation } from "react-router-dom";
    import Header from "./Header";
    import Header1 from "./Header1";
    import Routes from "./Routes";
    import Footer from "./Footer";
    
    function App() {
      const location = useLocation();
    
      // Render Header1 on Complain page and Header on all other pages
      const header = location.pathname === "/complain" ? <Header1 /> : <Header />;
    
      return (
        <>
          {header}
          <Routes />
          <Footer />
        </>
      );
    }
    
    export default App;