2

I am working on a reactjs project where I utilize react-router. I have multiple components to render, but not sure how to structure it. I am not getting expected results

Components

  • Authentication
  • SideBar
  • List
  • Detail

App.js

import ..... 
.... //some import statements
function App(){
  <BrowserRouter>
    <SideBar/>
    <Routes>
      <Route path="/" element={<List/>}/>
      <Route path="/detail" element={<Detail/>}/>
      <Route path="/authentication" element={<Authentication/>}/>
    </Routes>
  </BrowserRouter>
}

Here I have totally 4 components. The sidebar component will be common for both Detail and List component, & I don't want it to be visible for Authentication component.

Tried using the Outlet

App.js

import ..... 
.... //some import statements
function App(){
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<Authentication/>}/>
      <Route path="/app" element={<Container/>}/>
    </Routes>
  </BrowserRouter>
}

Container.js

import ..... 
.... //some import statements
function Container(){
    <SideBar/>
    <Routes>
      <Route path="/list" element={<List/>}/>
      <Route path="/detail" element={<Detail/>}/>
    </Routes>
}

Now the issue is when I navigate to http:///app it is showing a blank page with sidebar, which doesn't serve a purpose.

How this can be achieved ?

Badhusha
  • 88
  • 1
  • 1
  • 9

1 Answers1

1

I believe this is a working solution:

  • The sidebar is kept in the Layout component which uses the Outlet from react-router-dom
  • Having your auth route first without using the Layout
  • The other two routes are "contained" within the Layout component so these pages have the Sidebar

App.js

const App = () => {
  return (
    <BrowserRouter>
          <Routes>
            <Route path="/" element={<Authentication />} />
            <Route path="/" element={<Layout />}>
              <Route path="/list" element={<List />} />
              <Route path="/detail" element={<Detail />} />
            </Route>
          </Routes>
      </BrowserRouter>
  );
}

export default App;
export function Layout () {
    return (
        <div>
            <div className="container">
              <Sidebar />
              <Outlet />
            </div>
        </div>
    )
}

Note: Solution taken almost directly from This other question

p7dxb
  • 397
  • 8