Create a layout component using React

Quick and easy way to stop importing header/nav/footer components in routes

Wed, 05 Sep 2018

Are you tired of having to import your header and footer in every page component you create? If you’re anything like me, the answer to that question is hell yes! I will show you a quick way to create a layout component that will wrap around all of your page components

A basic React Router would look similar to this

  <Switch>
      <Route exact path="/" component={Home} />
      <Route exact path="/browse" component={Browse} />
  </Switch>

Your Home and Browse components would import your header and footer using the following logic

<div>
  <Header/>
    <div>
    	<p> Hi! </p>
    </div>
  <Footer/>
</div>

Normally that isn’t so bad if you have a few routes. Imagine having a lot of routes and having to do this in every route component. It can get messy and annoying. Instead do this

  <Switch>
    <Layout>
      <Route exact path="/" component={Home} />
      <Route exact path="/browse" component={Browse} />
    </Layout>
  </Switch>

We wrap all of our routes within a component named Layout. The contents of layout:

      <div>
        <Header/>
        {this.props.children}
        <Footer/>
      </div>

What happens here is that Layout is gets the active route from our router and loads the component within the section of this.props.children. Once you set up your Layout component, you can remove all header and footer references from your route components. You can also spice up your Layout by using packages such as React Helmet that inject scripts into your app and add metadata/link refs to your html’s head.

Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge