3

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

1 Answers1

6

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>
);
Uéslei Suptitz
  • 325
  • 1
  • 7
  • 2
    That working. Thanks for the answer Uéslei Suptitz. It helped me a lot. A small addition to your answer, In else block it should be wrapped using a element, never rendered directly. Please wrap your in a } /> ` – Denuke Dissanayake May 17 '22 at 19:32
  • Thanks! I'm from Brazil, so, i don't speak english very well – Uéslei Suptitz May 19 '22 at 13:22