iAmWhy
iAmWhy

Reputation: 427

Next.js 13 - Have different shared layouts

I now want to upgrade to Next 13. I have different navbars on my portfolio. How can I use a different navbar for the /about and /skills route than the home page and /contact route?

I thought you could now create different subfolders within the app directory, each with the layout.tsx file, but then corresponding unwanted routes are created.

I tried the following file structure:

/app/LayoutOne/layout.tsx
/app/LayoutOne/page.tsx
/app/LayoutOne/contact/page.tsx
/app/LayoutTwo/layout.tsx
/app/LayoutTwo/about/page.tsx
/app/LayoutTwo/skills/page.tsx

But then I had the following routes:

../LayoutOne
../LayoutOne/contact
../LayoutTwo/about
../LayoutTwo/skills

I don't want the layout parts in the URL's

Upvotes: 18

Views: 17406

Answers (2)

Yilmaz
Yilmaz

Reputation: 49182

Next.js has two layouts. "Root" and "regular". From docs

Root Layout : You can create a root layout that will apply to all routes of your application by adding a layout.js file inside the app folder. The root layout replaces the need for a custom App (_app.js) and custom Document (_document.js) since it applies to all routes.

Regular Layouts: You can also create a layout that only applies to a part of your application by adding a layout.js file inside a specific folder.

For example, you can create a layout.js file inside the "about" folder which will only apply to the route segments inside "about".

  • If you want to use one layout for more than 1 route, you can group them.

A route group can be created by wrapping a folder’s name in parenthesis: (folderName)

Note: The naming of route groups are only for organizational purposes since they do not affect the URL path.

enter image description here

  • Another way would be to create a custom BasePage component and wrap each page with BasePage. Because in your question you just want to use 2 different navbars. But what if some of the pages you don't need a navbar at all? For example https://codesandbox.io/ the main page has a navbar but the code playground pages have no navbar. Or maybe you would need a different background color for different pages. In each case, you just pass a prop to wrapper "BasePage" and handle the logic inside. the global layout file's role will be just applying top css rules or media rules.

Upvotes: 10

OGreeni
OGreeni

Reputation: 776

Use route grouping to avoid this behavior. Folder names that are enclosed in parentheses are ignored by the routing system.

Try this:

/app/(LayoutOne)/layout.tsx
/app/(LayoutOne)/page.tsx
/app/(LayoutOne)/contact/page.tsx
/app/(LayoutTwo)/layout.tsx
/app/(LayoutTwo)/about/page.tsx
/app/(LayoutTwo)/skills/page.tsx

To define the following routes:

../
../contact
../about
../skills

Upvotes: 35

Related Questions