0
0

Next.jsでのonClickイベントが発火しない問題の解決

Last updated at Posted at 2024-01-29

起きたこと

Next.jsでApp Routerを使用していた際に、カスタムしたbuttonコンポーネントでonClickが発火せず、ターミナルには以下のエラーがはかれていた。
Uncaught Error: invariant expected app router to be mounted at useRouter

問題のファイルがこちら↓

src/app/layout.tsx (間違えてます)
import type { Metadata } from "next";
import "../assets/styles/reset.scss";
import "../assets/styles/variable.scss";
import { Layout } from "@/components/Templates/Layout";
export const metadata: Metadata = {
  title: "Study Tracker Next",
  description: "Generated by create next app",
};
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <Layout>{children}</Layout>
    </html>
  );
}

原因

原因はapp/layout.tsxに本来必要なはずのbodyが抜けていたため、正常にhtmlの機能が使えていなかったようだ。

これで解決した

以下のようにhtmlタグ内にbodyタグを追加すると正常に動作した。

diff
- <Layout>{children}</Layout>
+    <body>
+     <Layout>{children}</Layout>
+    </body>

まとめ

App Routerでプロジェクトをセットアップするとデフォルトでbodyタグ無しのlayout.tsxが作成されるので、bodyタグの追加はすぐにやっておくことをおすすめします。

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