メインコンテンツまでスキップ

useSelectedLayoutSegment

useSelectedLayoutSegmentClient Componentのフックであり、呼び出されたレイアウトの1 階層下のアクティブなルート Segment を読み取ることができます。

これは、アクティブな子 Segment に応じてスタイルが変化するような、親レイアウト内のタブなどのナビゲーション UI を作成するのに役立ちます。

app/example-client-component.tsx
'use client'

import { useSelectedLayoutSegment } from 'next/navigation'

export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()

return <p>Active segment: {segment}</p>
}

Good to know:

  • useSelectedLayoutSegmentClient Componentのフックであり、レイアウトはデフォルトでServer Componentsであるため、useSelectedLayoutSegmentは通常、レイアウトにインポートされた Client Component から呼び出されます。
  • useSelectedLayoutSegment は、1 階層下の Segment のみを返します。全てのアクティブな Segments を返すには、useSelectedLayoutSegments を参照してください。

Parameters

const segment = useSelectedLayoutSegment(parallelRoutesKey?: string)

useSelectedLayoutSegmentオプションparallelRoutesKeyを受け取り、そのスロット内のアクティブなルート Segment を読み取ることができます。

Returns

useSelectedLayoutSegmentはアクティブな Segment の文字列を返します。存在しない場合はnullを返します。

例えば、以下のレイアウトと URL が与えられた場合、返される Segment は次のとおりになります。

LayoutVisited URLReturned Segment
app/layout.js/null
app/layout.js/dashboard'dashboard'
app/dashboard/layout.js/dashboardnull
app/dashboard/layout.js/dashboard/settings'settings'
app/dashboard/layout.js/dashboard/analytics'analytics'
app/dashboard/layout.js/dashboard/analytics/monthly'analytics'

useSelectedLayoutSegmentを使用すると、アクティブな Segment に応じてスタイルを変更可能な、active link component を作成できます。例えば、ブログのサイドバーの特集記事リストです。

app/blog/blog-nav-link.tsx
'use client'

import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'

// この client componentは、app/blog/layout.tsxにインポートされます。
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// /blog/hello-world`に遷移すると、'hello-world'が返されます。
// 選択されたレイアウトSegment
const segment = useSelectedLayoutSegment()
const isActive = slug === segment

return (
<Link
href={`/blog/${slug}`}
// リンクがアクティブかどうかに応じてスタイルを変更する。
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
app/blog/layout.tsx
// Client Componentを親レイアウト(Server Component)にインポートする。
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'

export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
const featuredPosts = await getFeaturedPosts()
return (
<div>
{featuredPosts.map((post) => (
<div key={post.id}>
<BlogNavLink slug={post.slug}>{post.title}</BlogNavLink>
</div>
))}
<div>{children}</div>
</div>
)
}

Version 履歴

VersionChanges
v13.0.0useSelectedLayoutSegment 導入