Search code examples
reactjsreact-router-dommern

How to hide a sidebar from a login page in react router


I'm trying to hide a sidebar component from showing when a user visits the signup or login page. In react-router-dom version 5, we could use a div tag inside the Switch but it has been replaced with the Route element and it throws an error when a div tag is used inside the Route element.

I'm totally a beginner who's trying to create a simple mern stack application.

import Sidebar from './components/sidebar/Sidebar';
import './App.css';
import Home from './pages/home/Home';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import UserList from './pages/userList/UserList';
import SignUp from "./components/sign-up.component";
import Login from "./components/login.component";
import Notfound from './components/Notfound/Notfound';

function App() {
  return (
    <Router>
      <div className="container">
      <Sidebar/>
        <Routes>
          <Route exact path="/" element={<Home/>}></Route>
          <Route exact path="/users" element={<UserList/>}></Route>
          <Route exact path="/login" element={<Login/>}></Route>
          <Route exact path="/signup" element={<SignUp/>}></Route>
          <Route element={<Notfound/>}></Route>
        </Routes>
      </div>
    </Router>
  );
}


export default App;

Solution

  • If you only want to render the Sidebar component on select routes then the pattern in RRDv6 is you create a layout wrapper that renders the Sidebar and an Outlet component for the nested Route components.

    Outlet

    An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.

    import { Outlet } from 'react-router-dom';
    
    const SidebarLayout = () => (
      <>
        <Sidebar />
        <Outlet />
      </>
    );
    

    Render the routes you want to have the Sidebar as nested children routes.

    function App() {
      return (
        <Router>
          <div className="container">
            <Routes>
              <Route element={<SidebarLayout/>}>
                <Route index element={<Home/>} />
                <Route path="/users" element={<UserList/>} />
                <Route path="*" element={<Notfound/>} />
              </Route>
              <Route path="/login" element={<Login/>} />
              <Route path="/signup" element={<SignUp/>} />
            </Routes>
          </div>
        </Router>
      );
    }