useSelectedLayoutSegment
useSelectedLayoutSegment は、呼び出し元の Layout より1階層下のアクティブなルートセグメントを読み取ることができるClient Componentフックです。
親 Layout 内のタブなど、アクティブな子セグメントに応じてスタイルが変わるナビゲーション UI に役立ちます。
app/example-client-component.tsx
TypeScript
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <p>Active segment: {segment}</p>
}補足:
useSelectedLayoutSegmentは Client Component フックであり、Layout はデフォルトで Server Components であるため、useSelectedLayoutSegmentは通常 Layout にインポートされている Client Component から呼び出されます。useSelectedLayoutSegmentは 1階層下のセグメントのみを返します。すべてのアクティブなセグメントを返すには、useSelectedLayoutSegmentsを参照してください。
パラメーター
const segment = useSelectedLayoutSegment(parallelRoutesKey?: string)useSelectedLayoutSegment は、オプションとして parallelRoutesKey を受け取ります。これにより、そのスロット内のアクティブなルートセグメントを読み取ることができます。
戻り値
useSelectedLayoutSegment は、アクティブなセグメントの文字列、または存在しない場合は null を返します。
例えば、以下の Layout と URL が与えられた場合、返されるセグメントは以下のようになります。
| Layout | アクセスされた URL | 返されるセグメント |
|---|---|---|
app/layout.js | / | null |
app/layout.js | /dashboard | 'dashboard' |
app/dashboard/layout.js | /dashboard | null |
app/dashboard/layout.js | /dashboard/settings | 'settings' |
app/dashboard/layout.js | /dashboard/analytics | 'analytics' |
app/dashboard/layout.js | /dashboard/analytics/monthly | 'analytics' |
例
アクティブなリンクコンポーネントの作成
useSelectedLayoutSegment を使用して、アクティブなセグメントに応じてスタイルが変わるアクティブなリンクコンポーネントを作成できます。例えば、ブログのサイドバーにおすすめ投稿リストを表示する場合です。
app/blog/blog-nav-link.tsx
TypeScript
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
// この*client*コンポーネントはブログ layout にインポートされます
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// `/blog/hello-world` に遷移すると、選択されたレイアウトセグメントに対して
// 'hello-world' が返されます
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
// リンクがアクティブかどうかに応じてスタイルを変更します
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}app/blog/layout.tsx
TypeScript
// Client Component を親の Layout(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>
)
}バージョン履歴
| バージョン | 変更内容 |
|---|---|
v13.0.0 | useSelectedLayoutSegment 導入時期:v13.0.0 |