1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.jsで戻るリンク

Last updated at Posted at 2022-05-02

以下のような感じで戻るリンクを実装しようとした所、

import { useRouter } from 'next/router'

<Link href='#' onClick={router.back()} >
  戻る
</Link>

エラーが発生
No Router Instance
next/routerがサーバー側(SSR、SSG)実行時に参照できないことが原因

解決策

  • コールバック定義とすることでリンクのクリック(=クライアント側)でのみ評価される
  • Linkのhrefは必須なので"#"を指定
import { useRouter } from 'next/router'

<Link href="#">
  <a onClick={() => { router.back() }} >
    戻る
  </a>
</Link>

参考

Next.JS Error: No router instance found

1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?