Gatsby: Does gatsby-plugin-layout support multiple layouts?

Created on 26 Oct 2018  路  6Comments  路  Source: gatsbyjs/gatsby

Summary

I'm trying to use gatsby-plugin-layout to persist state across pages as we used to be able to do in Gatsby v1. However, I need to use two different page layouts for different sets of pages. Is it possible to configure more than one layout? It's not in the docs and looking at the code it doesn't seem like there's support but wanted to check before submitting a feature request.

Relevant information

This was possible in v1 via https://v1.gatsbyjs.org/docs/creating-and-modifying-pages/#choosing-the-page-layout, and is obviously possible in v2 by importing different layout components as required. So it would be a really helpful feature and an obvious enhancement for the plugin.

question or discussion

Most helpful comment

All 6 comments

and is obviously possible in v2 by importing different layout components as required

And why doesn't work that for you? The layouts/index.js file persists the state, you wrap the pages with the layout components and use the state, e.g. via Context API.

@LekoArts My understanding of it is as described here. So in v1, the layout component wrapped around the page component, whereas in v2 the layout component is a child of the page component. The result being that whereas the layout component did not use to rerender on page transitions, it now does rerender each time.

How were you thinking of wrapping the pages themselves -- in gatsby-ssr.js and gatsby-browser.js files? If so I think that's essentially what gatsby-plugin-layout is doing.

Would love to hear opinions on this topic from the plugin's authors too (@pieh)?

You can conditionally render different wrapping layouts with gatsby-plugin-layout:
ie:

this is src/layouts/index.js (or different file you pointed to in plugin config)

export const ({ children, pageContext }) => {
  if (pageContext.useAlternativeLayout) {
    return <AlternativeLayout>{children}</AlternativeLayout>
  }

  return <RegularLayout>{children}</RegularLayout>
}

you would need to pass useAlternativeLayout (or something else to determine which layout to use for which page) to context of pages you create.

Nice idea @pieh, that worked well for me! Maybe worth adding to the docs?

Closing the issue as this resolves my question.

That's good idea - would you be interested in creating PR to add "handling multiple layouts" section to gatsby-plugin-layout docs?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

antoinerousseau picture antoinerousseau  路  139Comments

OleksandrSachuk picture OleksandrSachuk  路  75Comments

TuckerWhitehouse picture TuckerWhitehouse  路  69Comments

KyleAMathews picture KyleAMathews  路  97Comments

Jivings picture Jivings  路  112Comments