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 が導入されました。 |
この情報は役に立ちましたか?