コンテンツへスキップ
APIリファレンス関数useSelectedLayoutSegment

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/dashboardnull
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.0useSelectedLayoutSegmentが導入されました。