Home > OS >  How to hide certain Components for some Routes
How to hide certain Components for some Routes

Time:05-01

I want to hide Header and Footer Component in some routes, e;g for path="/invoice/:id/print"

I have an app with this type of layout using react-router-dom v5

<Router>
        <Header />

        <main className="py-0 px-0">
          <div>
            <Container fluid>
              <Switch>
                <Route path="/" component={HomeScreen} exact />
                <Route path="/invoices" component={Invoices} exact />
                <Route path="/invoice/:id/print" component={InvoicePrint} exact />
                <Route path="/billing/invoice/create" component={InvoiceCreate} exact />
                <Route path="*" exact>
                  <Error404 />
                </Route>
              </Switch>
            </Container>
          </div>
        </main>

        <Footer />
      </Router>

The problem is if I go to

<Route path="/invoice/:id/print" component={InvoicePrint} exact />

Then Header and Footer also get rendered. But I want to hide them for this specific route. So how can I do that?

I'm using react-router version 5

CodePudding user response:

That depends on how many pages should render the Header and Footer components. If you want to render them on just a few pages, the simplest solution will be to move them to the components/pages where you'd like to render them.

If you'd like to hide them in just one or two places you can use the useRouteMatch hook.

You can also build some abstractions to simplify the readability a bit: let's make the Layout component, which will accept a prop (like renderHeaderAndFooter (you can change the name of course

  • Related