0
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】Intercepting Routesを使用したモーダルが閉じない場合の対処法【AppRouter】

Last updated at Posted at 2023-07-14

状況

次のようなディレクトリ構成でIntercepting Routesを使用したモーダルを作成したところモーダル内のボタンから他の画面へ遷移した際にモーダルが表示されたままになりました。

app
├── @modal
│   ├── [...catchAll]
│   │   └── page.tsx
│   ├── default.tsx
│   └── users
│       └── [id]
│           └── page.tsx
└── users
    ├── [id]
    │   └── page.tsx
    └── page.tsx

対処法

./@modal/users/[id]/page.tsxまたはその子コンポーネントでusePathnameを使用して/users/を含む場合にのみ<Modal></Modal>を返すようにすると改善します。

'use client'
import { usePathname } from 'next/navigation'

export default function Sample() {
	const pathname = usePathname()
	const shouldShowModal = pathname.includes("/users/")

	return shouldShowModal && <Modal>{/* ... */}</Modal>
}

公式ドキュメントに他のURLへ遷移する際には[...catchAll]を使用するように記載がありますが、これがうまく機能していないようです。[...catchAll]は削除しても正常に動作します。

参考

上記の中で@modal直下にnullを返すpage.tsxを作成する方法が記載されていますが、こちらは@modal/page.tsxに対応するURL(app/@modal/page.tsxの場合は/)に遷移する際にのみ効果があるようです。

0
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
0
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?