2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js】AppフォルダでのRoute Group

Posted at

初めに

Next.jsを使用してアプリケーションを作成している際、複数ページまとめてレイアウトを変更したくなったため方法を調べていたらRoute Groupsなるものが見つけられたので、備忘録も兼ねて記事にしようと思いました。

レイアウトの設定方法

Next.jsでは、ページのレイアウトを設定するファイルとしてlayout.tsxを使用します。

app
 ├ home/
 ├ articles/
 ├ settings/
 │     └ profile/
 ├ page.tsx
 └ layout.tsx

上記のようなフォルダ構成を想定すると、appディレクトリにlayout.tsxを作成してレイアウトを設定するとappフォルダ以下のファイルには全てlayout.tsxのレイアウトが適用されます。

ですが、appフォルダ以下のファイルには全てapp/layout.tsxが適用されてしまうため、ファイルごとのレイアウトの変更はできなくなってしまいます。

app
 ├ home/
 ├ articles/
 ├ settings/
 │     ├ profile/ 
 │     └ layout.tsx
 ├ page.tsx
 └ layout.tsx

もし、上記のようにsettingsフォルダの直下に新しくlayout.tsxを作成したとしても、app/layout.tsxapp/settings/layout.tsxの両方のレイアウトが適用されてしまい、画面がおかしなことになってしまいます。

それを解決する方法がRoute Groupになります。

Route Groupの設定方法

Route Groupの設定方法は括弧で囲まれたフォルダを作成するだけです。
具体例)

app
 ├ home/
 ├ articles/
 ├ (settings)/
 │     └ settings/
 │          ├ profile/ 
 │          └ layout.tsx
 ├ page.tsx
 └ layout.tsx

そして、上記のように括弧で囲まれたフォルダ直下にlayout.tsxを配置してレイアウト設定を行うことによって、(settings)フォルダ以下のファイル全てにapp/(settings)/layout.tsxのみが適用されるようになります。

これで、任意のフォルダのみに適用されるレイアウトを作成することができます。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?