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 App Routerで「前の画面に戻る」処理を実装する方法

0
Posted at

Next.jsApp Routerで画面を作っていると、
「戻る」ボタンや「保存後の遷移」で直前の画面に戻したい
というケース、よくありませんか?

単純に router.replace("/固定URL") を書いてしまうと、
「どのページから来ても同じ場所に飛ばされる」のでUXが微妙です。

今回は、直前の画面に戻る実装方法を紹介します。


📌 使用ツール

  • Next.js(App Router)
  • TypeScript(任意)

📌 例) 戻るボタンで「元の画面へ戻す」

  • onSubmitで保存する場合も、下記のhandleBack()で簡単に呼ぶことができます
"use client";

import { useRouter } from "next/navigation";

export default function BackButton() {
  const router = useRouter();

  const handleBack = () => {
    if (typeof window !== "undefined" && window.history.length > 1) {
      router.back(); // 直前のページへ
    } else {
      router.replace("/"); // ← ホーム画面にフォールバック
    }
  };

  return (
    <button
      onClick={handleBack}
    >
      戻る
    </button>
  );
}

👉 typeof window !== "undefined"

  • Next.jsSSR(サーバーサイドレンダリング)されるので、サーバー側では window が存在しません
  • このチェックで「今はブラウザ上かどうか」を判定しています

👉 window.history.length > 1

  • ブラウザの履歴が1より大きければ「前のページ」がある
    = 「直前のタブに戻れる履歴があるかどうか」を判定
  • そうでなければ直リンクで来た可能性が高いので、フォールバックへ遷移

📌 まとめ

  • router.back() を使えば直前の画面に戻れる
  • 直リンク時の安全策として、ホームに戻す router.replace("/") を用意すると安心
  • ボタンでも保存処理する場合、同じ関数(handleBack)を呼ぶだけで共通化できる
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?