Home > Mobile >  Show header for all pages except home page in ReactJS
Show header for all pages except home page in ReactJS

Time:01-30

I am very new to ReactJS and I want the header to be shown for all pages except the Home page <Route path='/' element={ }/>.

function App() {
  return (
    <div className="App">
      <Router>
        <Header/>
          <Routes>
              <Route path='/' element={ <Home/>}/>
              <Route path='/Breakfast' element={<Breakfast/>}/>
              <Route path='/Lunch' element={<Lunch/>}/>
              <Route path='/Snacks' element={<Snacks/>}/>
              <Route path='/Dinner' element={<Dinner/>}/>
              <Route path='/Drinks' element={<Drinks/>}/>
              <Route path='/NightLife' element={<NightLife/>}/>
          </Routes>
          <Footer/>
      </Router>
    </div>
  );
}

CodePudding user response:

Anup will you explain your question with some images?

CodePudding user response:

One option might be to move your <Header /> component into a <Layout /> component (which is something I usually do). Reason why is that you can't conditionally check a route outside of a <Router /> context, meaning you can't do it in your <App /> component.

The layout would take a children prop and check if the current route is the homepage:

const Layout = ({ children }) => {
  const { pathname } = useLocation();

  return (
    <div>
      {pathname !== "/" ? <Header /> : null}
      <div>{children}</div>
    </div>
  );
};

Check out an example here.

CodePudding user response:

You could wrap the whole page in a Layout and only render the Header if the current page is not the homepage.

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="/blogs" element={<Blogs />} />
        </Routes>
      </Router>
    </div>
  );
}

And providing the Layout like this:

const Layout = () => {
  return (
    <>
      {!(path="/") && <Header />}
      <Outlet />
      <Footer />
    </>
  )
};

W3Schools has a pretty good documentation for this!

  •  Tags:  
  • Related