skip to Main Content
import { BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom';
import { Home } from '../Pages/Home';
import { Login } from '../Pages/Login';
import { Register } from '../Pages/Register';

function App() {
  return (
        <Router>
              <Navbar/>
              <Routes>
                <Route path='/home' element={ <Home />}></Route>
                <Route path='/login' element={ <Login />}></Route>
                <Route path='/register' element={ <Register />}></Route>
                <Route path="*" element={ <h1>Page Not Found</h1>}></Route>
              </Routes>
        </Router>
    
  );
}

export default App;

I can’t think a logic how to make it disappear when it is directed in page not found.

2

Answers


  1. Wich version are you using? I think you can use the useLocation() function. Something like this:

    function App() {
      const location = useLocation();
    
      const validRoutes = ['/home', '/login', '/register'];
    
      const isNavbarVisible = validRoutes.includes(location.pathname);
    
      return (
        <Router>
          {isNavbarVisible && <Navbar />}
          <Routes>
            <Route path='/home' element={<Home />} />
            <Route path='/login' element={<Login />} />
            <Route path='/register' element={<Register />} />
            <Route path="*" element={<h1>Page Not Found</h1>} />
          </Routes>
        </Router>
      );
    }
    
    export default App;
    

    I have used this a long time ago. Maybe still work

    Login or Signup to reply.
  2. First, we should change the URL of the NotFoundPage when accessing invalid address to be "/404" as the following:

    //In App.tsx  
    <Routes>
      <Route path="/" element={<AppLayout/>}>
      ...
        <Route path="/404" element={<NotFoundPage />} />
        <Route path="*" element={<Navigate replace to="/404" />} />
      </Route>
    </Routes>
    

    After that, we can easily detect if we are in NotFoundPage to remove the NavBar

    const AppLayout = ({ links }: NavigationProps) => {
      const { pathname } = useLocation();
      const isNotFoundPage = useMemo(() => pathname === "/404", [pathname]);
      ...
      {!isNotFoundPage && (
      <NavBar
        className="navigator-container"
        sx={{ position: "relative", paddingRight: "0px !important" }}
      >
      ...
      </NavBar>)}
    
      <main>
        <Outlet />
      </main>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search