In this article, we will see how to use the NextJs route groups to set a shared layout for multiple pages in the app folder.
Introducing the route groups in NextJs 13
Let's say we have the following files in the app folder:
/app
page.js -> maps to: /
/red
page.js -> maps to: /red
/blue
page.js -> maps to: /blue
/green
page.js -> maps to: /green
For the /red
and /blue
routes we want to set a shared layout, but we don't want to have this layout on the /green
route.
In order to do this we will need to use the route groups from NextJs.
A route group is created by wrapping a folderβs name in parenthesis:
(nameOfFolder)
By adding a route group we are breaking out of the NextJs route system. The folders written in round brackets are not included in the application routes.
So, if we will add put the red
and blue
folders in a folder named (sharedLayout)
, we will still have the same routes as before:
/app
page.js -> maps to: /
(sharedLayout)
/red
page.js -> maps to: /red
/blue
page.js -> maps to: /blue
/green
page.js -> maps to: /green
We can use the route groups to better organize our code.
Adding shared layouts for multiple pages
But, one cool thing is that we can also use route groups to share layouts between multiple pages with the same root folder. So, if we will add a layout.js
file in the (sharedLayout)
folder:
/app
page.js
/(sharedLayout)
layout.js
/red
page.js
/blue
page.js
/green
page.js -> maps to: /green
Then the /red
and /blue
pages will have the same shared layout file:
/app/(sharedLayout)/layout.js
You can check out a small app example with NextJs shared layouts here. Below you have the screenshots of the pages that share the same layout file: /red
and /blue
:
And speaking of layouts I've made this example for how to make a responsive sidebar layout in NextJs
π 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
π 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.