Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to hide certain Components for some Routes

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

>Solution :

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 😄)).

Layout component:

const Layout = ({ renderHeaderAndFooter, children }) => (
  <div>
    {renderHeaderAndFooter && (
      <Header />
    )}
    {children}
    {renderHeaderAndFooter && (
      <Footer />
    )}
  </div>
)

and the place of usage:

const HomeScreen = () => (
  <Layout renderHeaderAndFooter={true}>
    // make stuff
  </Layout>
)
const Invoices = () => (
  <Layout renderHeaderAndFooter={false}>
    // make stuff
  </Layout>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading