useSelectedLayoutSegment
useSelectedLayoutSegment
は、呼び出されたレイアウトの**1 つ下のレベル**のアクティブなルートセグメントを読み取ることを可能にする**クライアントコンポーネント**フックです。
アクティブな子セグメントに応じてスタイルを変更する、親レイアウト内のタブなどのナビゲーション 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>
}
知っておくと良いこと:
useSelectedLayoutSegment
はクライアントコンポーネントフックであり、レイアウトはデフォルトでサーバーコンポーネントであるため、useSelectedLayoutSegment
は通常、レイアウトにインポートされるクライアントコンポーネントを介して呼び出されます。useSelectedLayoutSegment
は、1 つ下のレベルのセグメントのみを返します。すべてのアクティブなセグメントを返すには、useSelectedLayoutSegments
を参照してください。
パラメーター
const segment = useSelectedLayoutSegment(parallelRoutesKey?: string)
useSelectedLayoutSegment
は、オプションで parallelRoutesKey
を受け入れることができ、それにより、そのスロット内のアクティブなルートセグメントを読み取ることができます。
戻り値
useSelectedLayoutSegment
は、アクティブなセグメントの文字列を返すか、存在しない場合は null
を返します。
たとえば、以下のレイアウトと URL が与えられた場合、返されるセグメントは次のようになります。
レイアウト | アクセスされた 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
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
// This *client* component will be imported into a blog layout
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// Navigating to `/blog/hello-world` will return 'hello-world'
// for the selected layout segment
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
// Change style depending on whether the link is active
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
app/blog/layout.tsx
// Import the Client Component into a parent 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 が導入されました。 |
お役に立ちましたか?