作成:2026-06-22最終更新:2026-06-22
このドキュメントをあなたの好きなAIアシスタントに参照してくださいChatGPTClaudeDeepSeekGoogle AI modeGeminiPerplexityMistralGrok
このページとあなたの好きなAIアシスタントを使ってドキュメントを要約します
バージョン履歴
- "usePathnameユーティリティを追加"v10.0.02026/6/23
- "履歴の初期化"v8.2.02026/6/22
このページのコンテンツはAIを使用して翻訳されました。
英語の元のコンテンツの最新バージョンを見るEdit this doc
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy
Copy doc Markdown to clipboard
Preact 統合: usePathname フックのドキュメント
usePathname フックは、ロケールセグメントが削除された現在のブラウザパス名(pathname)を返します。これは、ロケールプレフィックスを手動で削除することなく、ロケールを考慮したナビゲーション(例:どのナビゲーションアイテムがアクティブかを判定する)を構築するのに役立ちます。
Preact での usePathname のインポート
typescript
コードをコピー
コードをクリップボードにコピー
import { usePathname } from "preact-intlayer";概要
usePathname は window.location.pathname を読み取り、getPathWithoutLocale 経由でロケールプレフィックスを削除します。ブラウザが popstate イベント(戻る/進む ナビゲーション)を発生させるたびにコンポーネントを再レンダリングします。サーバーサイドレンダリング(SSR)中は空の文字列を返します。
使用方法
src/components/NavItem.tsx
コードをコピー
コードをクリップボードにコピー
import type { FunctionComponent } from "preact";import { usePathname } from "preact-intlayer";type NavItemProps = { href: string; label: string;};const NavItem: FunctionComponent<NavItemProps> = ({ href, label }) => { const pathname = usePathname(); const isActive = pathname === href; return ( <a href={href} aria-current={isActive ? "page" : undefined}> {label} </a> );};export default NavItem;戻り値
テーブルのすべての内容を表示
テーブルをモーダルで開き、すべてのデータを明確に表示
| 型 | 説明 |
|---|---|
string | ロケールプレフィックスを含まない現在のパス名。サーバーサイドレンダリング(SSR)中は空の文字列を返します。 |
動作
- ロケールの削除 (Locale stripping): 先頭のロケールセグメントを削除します(例:
/ja/dashboard→/dashboard)。 - リアクティブ: ブラウザの戻る / 進むナビゲーション(
popstateイベント)時に自動的に更新されます。 - SSR セーフ:
windowが利用できない場合は""を返します。 - クリーンアップ: コンポーネントのアンマウント時に、
popstateリスナーは自動的に削除されます。
例
src/components/Sidebar.tsx
コードをコピー
コードをクリップボードにコピー
import type { FunctionComponent } from "preact";import { usePathname } from "preact-intlayer";const links = [ { href: "/dashboard", label: "ダッシュボード" }, { href: "/settings", label: "設定" },];const Sidebar: FunctionComponent = () => { const pathname = usePathname(); return ( <nav> {links.map(({ href, label }) => ( <a key={href} href={href} style={{ fontWeight: pathname === href ? "bold" : "normal" }} > {label} </a> ))} </nav> );};export default Sidebar;関連ドキュメント
useLocale— 現在のロケールとロケールスイッチャーgetPathWithoutLocale— このフックで使われているベースのユーティリティ