Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not render a Header on landing(Login page) page but always on all other pages in react-router v6?

I am trying to create a website that has a landing page (Login) without a header, but once the user has logged in, all subsequent pages will have the header. I have tried the following but the syntax is incorrect and therefore does not work. Please can someone advise?

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Login from '..path for landing';
import component1 from '..path for component1';
import component2 from '..path for component2';

const App = () => {
  return (
    <Router>
      <Routes>
        <Route exact path="/" element={<Login />} />
        
        <Header />
        
        <Route path="/component1" element={<component1 />} />
        <Route path="/component2" element={<component2 />} />
      </Routes>
    </Router>
  );
}
like image 559
johnDoe Avatar asked Oct 18 '25 07:10

johnDoe


1 Answers

Create a layout component that renders the Header component and an Outlet component for nested routes to be rendered into.

Exmaple:

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

const AuthLayout = () => {
  // ... perhaps some authentication logic to protect routes?
  return (
    <>
      <Header />
      <Outlet />
    </>
  );
};

...

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Login />} />
        <Route element={<AuthLayout />}>
          <Route path="/component1" element={<component1 />} />
          <Route path="/component2" element={<component2 />} />
        </Route>
      </Routes>
    </Router>
  );
}
like image 184
Drew Reese Avatar answered Oct 20 '25 16:10

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!