0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】ページをリロードせずURLを変更する方法

Posted at

ネイティブのHistory APIを使用して、ページをリロードせずにブラウザの履歴スタックを更新できます。

window.history.pushStateの使用方法

pushStateメソッドを使用すると、ブラウザの履歴スタックに新しいエントリを追加できます。これにより、ユーザーは前の状態に戻ることができます。例えば、商品のリストをソートする際に利用します。

'use client'

import { useSearchParams } from 'next/navigation'

export default function SortProducts() {
  const searchParams = useSearchParams()

  function updateSorting(sortOrder: string) {
    const params = new URLSearchParams(searchParams.toString())
    params.set('sort', sortOrder)
    window.history.pushState(null, '', `?${params.toString()}`)
  }

  return (
    <>
      <button onClick={() => updateSorting('asc')}>Sort Ascending</button>
      <button onClick={() => updateSorting('desc')}>Sort Descending</button>
    </>
  )
}
  • useSearchParamsを使用して現在の検索パラメータを取得します
  • updateSorting関数でソート順を設定し、pushStateを呼び出してURLを更新します

window.history.replaceStateの使用方法

replaceStateメソッドを使用すると、現在の履歴エントリを置き換えることができます。これにより、ユーザーは前の状態に戻ることができません。例えば、アプリケーションのロケールを変更する際に使用します。

'use client'

import { usePathname } from 'next/navigation'

export function LocaleSwitcher() {
  const pathname = usePathname()

  function switchLocale(locale: string) {
    // 例: '/en/about' または '/fr/contact'
    const newPath = `/${locale}${pathname}`
    window.history.replaceState(null, '', newPath)
  }

  return (
    <>
      <button onClick={() => switchLocale('en')}>English</button>
      <button onClick={() => switchLocale('fr')}>French</button>
    </>
  )
}
  • usePathnameを使用して現在のパスを取得します
  • switchLocale関数で新しいロケールに基づいたパスを生成し、replaceStateを呼び出してURLを更新します
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?