1

In the following react app, I have a Layout component which contains a Navbar and a Footer (these are the same for all pages and thus they never need to be re-rendered) ...

<BrowserRouter>
   <Layout>
      <Navbar />
      <Footer />
      <Routes>
         <Route path="/" element={<Home />} />
         <Route path="/about" element={<About />} />
         <Route path="/contact" element={<Contact />} />
      </Routes>
   </Layout>
</BrowserRouter>

... and a Content and a Sidebar -- these depend on the page, and thus they are rendered from the page component, for example:

const About = () => {
    return (
       <>
          <Content>
             ...
          </Content>
          <Sidebar>
             ...
          </Sidebar>
       </>
   )
}

I want Contact to use a different layout: same Navbar and a Footer but no Sidebar and different dimensions for content (i.e. I cannot just not render the sidebar). Is there a way to do this without having to declare <Navbar/> and <Footer/> in multiple places?

The only way I see is to use nested layouts, i.e. a parent layout with navbar and footer, and then child layouts either with sidebar and smaller content or without sidebar and bigger content. However, I'd like to avoid nested layouts if possible.

arb
  • 11
  • 2
  • 1
    You could use [matchRoutes](https://reactrouter.com/en/main/utils/match-routes) (or matchPath, or check Location), and use that to conditionally render SideBar (or any other component). There's an example `matchRoutes` usage [here](https://stackoverflow.com/a/73530163/5774952). – Zac Anger Dec 18 '22 at 02:25
  • I do not only need to exclude the SideBar, I also need different dimensions for Content. The dimensions are defined in Layout. (I have edited the question to clarify this.) – arb Dec 18 '22 at 13:34

0 Answers0