1

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

Hesam
  • 450
  • 2
  • 11
atropa belladona
  • 474
  • 6
  • 25

3 Answers3

3

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>
)
Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25
2

simple way is to trigger your current route by using useRouteMatch in every component you want like:

 const match = useRouteMatch("/invoice/:id/print"); // import { useRouteMatch } from "react-router-dom";


 return !!match ? <></> : <Footer/> //or Header

check this

Hesam
  • 450
  • 2
  • 11
1

You have to update the Header and Footer components by adding a listener during the rendering phase of the component : componentDidMount()

Fetch the called component : const shouldHide = useRouteMatch("/invoice/:id/print") || useRouteMatch("/other/route");

return (
 !shoudlHide && <Header />
)

AceneKASDI
  • 339
  • 3
  • 8