Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Navbar and a Sidebar inside the React Router v6 Routes? [duplicate]

I'm building a React application and for routing use React Router V6. In the application, I have a Navigation Bar at the top and a Sidebar on the left side of the application. Using the sidebar I'm rendering different pages in the application (inside the 'screens-section-container' div as my below code shows).

I want to add a Login page. But It needs to be full screen. If only logged users can see the Navigation Bar and the Side Bar. But with Router v6 we cannot nest other elements than Route or React.Fragment within the Routes. If I added Routes outside the Navbar component tag it gives an error. Error: [Navbar] is not a <Route> component. All component children of <Routes> must be a <Route or <React.Fragment>.

How can I add the login route to this?

Users should first see the full-screen login page and when successfully login can see the NavBar and the Sidebar.

Code of App.tsx like this,

const App = () => {
  return (
    <div className="App">
      <BrowserRouter>
        <Navbar />
        <div className="screens-container">
          <Sidebar />
          <div className='screens-section-container'>
            <Routes>
              <Route path='/' element={<Home />} />
              <Route path='/customers' element={<Customers />} />
              <Route path='/products' element={<Products/>}/>
              <Route path='/transactions' element={<Transactions />} />
              <Route path='/users' element={<Users />} />
            </Routes>
          </div>
        </div>
      </BrowserRouter>
    </div>
  );
}

Updated: Another answer is even here How do I render components with different layouts/elements using react-router-dom v6

like image 948
Denuke Dissanayake Avatar asked Sep 02 '25 03:09

Denuke Dissanayake


1 Answers

Have you tried something like:

return (
  <div className="App">
    <BrowserRouter>
    {logged ? (
      <>
      <Navbar />
      <div className="screens-container">
        <Sidebar />
        <div className='screens-section-container'>
          <Routes>
            <Route path='/' element={<Home />} />
            <Route path='/customers' element={<Customers />} />
            <Route path='/products' element={<Products/>}/>
            <Route path='/transactions' element={<Transactions />} />
            <Route path='/users' element={<Users />} />
          </Routes>
        </div>
      </div>
      </>
    ): (
      <Routes>
        <Route path='/' element={<Login />} />
      </Routes>
    )}
    </BrowserRouter>
  </div>
);
like image 187
Uéslei Suptitz Avatar answered Sep 05 '25 00:09

Uéslei Suptitz