Parallel Routes
Parallel Routes(병렬 라우팅?)를 사용하면 동일한 레이아웃에서 하나 이상의 페이지를 동시에 또는 조건부로 렌더링 할 수 있다. 소셜 사이트의 대시보드 및 피드와 같은 앱의 동적인 섹션의 경우 Parallel Routing을 사용하여 복잡한 라우팅 패턴을 구현할 수 있다.
예를 들어 다음과 같이 team 및 analytics 페이지를 동시에 렌더링 할 수 있다.
Parallel Routing을 사용하면 개별적으로 스트리밍되는 각 route에 대해 개별적인 오류 및 로딩 상태를 정의할 수 있다.
또한 Parallel Routing을 사용하면 인증 상태와 같은 특정 조건에 따라 슬롯을 조건부로 렌더링 할 수 있다. 이렇게 하면 동일한 URL에서 완전히 구분된 코드를 사용할 수 있다.
Convention
Parallel Route는 명명된(named) 슬롯을 사용해서 생성된다. 슬롯은 @folder 컨벤션으로 정의되고 레이아웃과 동일한 레벨의 props로 전달된다.
* 슬롯은 route segment가 아니기 때문에 URL 구조에 영향을 주지 않는다. /@team/members 파일 경로는 /members에서 접근할 수 있다.
예를 들어 다음 파일구조는 두 개의 명시적 슬롯인 @analytics 및 @team을 정의한다.
위의 폴더 구조는 app/layout.js 내의 컴포넌트가 이제 @analytics 와 @team 슬롯을 props로 받아들이고 children props와 함께 병렬로 렌더링 할 수 있음을 의미한다.
// app/layout.tsx
export default function Layout(props: {
children: React.ReactNode
analytics: React.ReactNode
team: React.ReactNode
}) {
return (
<>
{props.children}
{props.team}
{props.analytics}
</>
)
}
* 알면 좋은것 : chilren prop은 폴더에 매핑할 필요가 없는 암묵적인 슬롯이다. 즉, app/page.js는 app/@children/page.js와 동일하다.
Unmatched Routes
기본적으로 슬롯 내에서 렌더링되는 컨텐츠는 현재 URL과 일치한다.
일치하지 않는 슬롯의 경우 Next.js가 렌더링하는 컨텐츠는 라우팅 기법과 폴더 구조에 따라 다르다.
default.js
현재 URL을 기준으로 Next.js가 슬롯의 활성화 상태를 복구할 수 없을 때 fallback(대체)으로 렌더링할 default.js 파일을 정의할 수 있다.
다음과 같은 폴더 구조를 고려해보자. @team 슬롯은 settings 디렉토리가 있지만 @analytics는 없다.
root인 / 에서 /settings로 이동하는 경우 렌더링되는 컨텐츠는 탐색 유형과 default.js 파일의 가용성(availability)에 따라 달라진다.
With @analytics/default.js | Without @analytics/default.js | |
Soft Navigation | @team/settings/page.js and @analytics/page.js |
@team/settings/page.js and @analytics/page.js |
Hard Navigation | @team/settings/page.js and @analytics/default.js |
404 |
Soft Navigation
Soft navigation에서 Next.js는 슬롯이 현재 URL과 일치하지 않더라도 슬롯의 이전 활성화 상태를 렌더링한다.
Hard Navigation
전체 페이지를 다시 로딩해야하는 Hard Navigation에서 Next.js는 먼저 일치하지 않는 슬롯의 default.js파일을 렌더링하려고 한다. 렌더링에 실패하면 404가 렌더링된다.
* 일치하지 않는 route에 대한 404는 parallel 렌더링되지 않아야 하는 route를 실수로 렌더링 하지 않도록 보호한다.
useSelectedLayoutSegment(s)
useSelectedLayoutSegment와 useSelectedLayoutSegments는 해당 슬롯 내부의 활성화 route segment를 읽을 수 있는 parallelRoutesKey를 받아들인다.
// app/layout.tsx
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default async function Layout(props: {
//...
authModal: React.ReactNode
}) {
const loginSegments = useSelectedLayoutSegment('authModal')
// ...
}
사용자가 @authModal/login 또는 URL바의 /login으로 이동하면 loginSegments는 'login' 문자열과 동일하다.
Examples
Modals
Parallel Routing은 modal을 렌더링하는데 사용할 수 있다.
@authModal 슬롯은 일치하는 경로(예를 들면 /login)로 이동하여 표시할 수 있는 <Modal> 컴포넌트를 렌더링한다.
// app/layout.tsx
export default async function Layout(props: {
// ...
authModal: React.ReactNode
}) {
return (
<>
{/* ... */}
{props.authModal}
</>
)
}
// app/@authModal/login/page.tsx
import { Modal } from 'components/modal'
export default function Login() {
return (
<Modal>
<h1>Login</h1>
{/* ... */}
</Modal>
)
}
활성화된 상태가 아닐 때 Modal의 내용이 렌더링되지 않도록 하려면 null을 반환하는 default.js 파일을 만들 수 있다.
// app/@authModal/login/default.tsx
export default function Default() {
return null
}
Dismissing a modal
클라이언트 탐색을 통해 Modal이 시작된 경우(예 : <Link href="/login">를 사용할때) router.back()을 호출하거나 Link 컴포넌트를 사용하여 Modal을 해제(dismiss)할 수 있다.
// app/@authModal/login/page.tsx
'use client'
import { useRouter } from 'next/navigation'
import { Modal } from 'components/modal'
export default async function Login() {
const router = useRouter()
return (
<Modal>
<span onClick={() => router.back()}>Close modal</span>
<h1>Login</h1>
...
</Modal>
)
}
* Modal에 대한 자세한 내용은 Intercepting Routes 섹션에서 다룬다.
다른곳으로 이동하여 modal을 해제하려고 하는 경우 catch-all route를 사용할 수도 있다.
// app/@authModal/[...catchAll]/page.tsx
export default function CatchAll() {
return null
}
* Catch-all routes는 default.js 보다 우선한다.
Conditional Routes
Parallel Routes를 사용하여 조건부 라우팅을 구현할 수 있다. 예를 들어 인증 상태에 따라 @dashboard 또는 @login route를 렌더링 할 수 있다.
// app/layout.tsx
import { getUser } from '@/lib/auth'
export default function Layout({
dashboard,
login,
}: {
dashboard: React.ReactNode
login: React.ReactNode
}) {
const isLoggedIn = getUser()
return isLoggedIn ? dashboard : login
}
Reference
- https://nextjs.org/docs/app/building-your-application/routing/parallel-routes
Routing: Parallel Routes | Next.js
Using App Router Features available in /app
nextjs.org
'개인공부' 카테고리의 다른 글
Next.js Docs (11) Route Handlers (0) | 2023.07.08 |
---|---|
Next.js Docs (10) Intercepting Routes (0) | 2023.07.05 |
Next.js Docs (8) Error Handling (0) | 2023.06.28 |
Next.js Docs (7) Loading UI and Streaming (0) | 2023.06.24 |
Next.js Docs (6) Dynamic Routes (0) | 2023.06.20 |
댓글