ファランクス by ponta

Nextjs(react) : 基礎②

useRouter()

import { useRouter } from "next/navigation";
---
const router = useRouter();
---
try {
      const { error: signInError } = await supabase.auth.signInWithPassword({
        email: email,
        password: password,
      });
      await router.push("/dashboard"); // ログイン後にリダイレクトする

** importするときは next/navigation でインポートする **

そうでないと Mouted エラーになる

https://nextjs.org/docs/messages/next-router-not-mounted

https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating


routerの使い方は上記のような感じでページ移動に使える

フォルダ構成例

  • HeaderやFooterの配置例 
  • あまりいじらないコンポーネントは分けた方がわかりやすい
  • componentsやlibフォルダはappの外に置いた方がわかりやすい
例:src/ app , components , lib /

() , ルーティングに含まない

  • ()でくくるとルーティングに含まれないフォルダになる
  • 機能ごとに分ける使い方
例:app/(auth)/login.jsx , logout.jsx

基本のレイアウト

<html lang="ja">
      <ThemeProvider
        attribute="class"
        defaultTheme="dark"
        enableSystem
        disableTransitionOnChange
      >
        <body className={inter.className}>
          <Header />
          {children}
          <Footer />
        </body>
      </ThemeProvider>
    </html>
  • footer と header はapp/layout.jsx , body内に配置

next/image

nextjsの <Image /> は src , alt , width , height が必須だが、

sizeに関しては fill だけでもOK onject-coverと合わせると良い

例:

<Image src={url} alt="image" fill className="object-cover"></Image>

***********

でもあまり使わない方がいいかも

***********

データベースに絡めて使うとエラーに

 has "fill" and a height value of 0. This is likely because the parent element of the image has not been styled to have a set height.

いつも通り width={} height={} に直すとうまくいった

外部の画像 / nextConfig.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      { protocol: "https", hostname: "img.clerk.com" },
      { protocol: "https", hostname: "res.cloudinary.com" },
      { protocol: "https",hostname: "images.pexels.com }
    ],
  },
};

module.exports = nextConfig;

remotePatternsの配列内に足していく。

  • topページのURLではなく、画像なら画像を開いたときのURLを参照する
  • OK:images.pexels.com , X:www.pexels.com

ルーティングとpage.tsx

  • app内のフォルダはすべてルーティングになるわけではない
  • page.tsxがあるとルートになる
  • page.tsxが無い場合はフォルダの先頭に[_]アンダーバーを付ける等で区別するのも有り

appより下層のlayout.jsx

  • app下のlayout.jsxより下の階層でもlayout.jsxは作れる
例:app/blog/page.jsx , layout.jsx/[slug]/page.jsx
layout.jsx
===
import React from "react";

const BlogLayout = ({ children }) => {
  return (
    <>
      <div>BlogLayout</div>
      {children}
    </>
  );
};

export default BlogLayout;
  • blogルーティング以下で共通ではない部分をchildrenで受け取る

← Go home