状況
次のようなディレクトリ構成で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
の場合は/
)に遷移する際にのみ効果があるようです。