ファランクス by ponta

Nextjs(react) : 基礎

環境変数

process.env.NEXT_PUBLIC_API_KEY

useClient” が先頭にあったり、useState, useEffect を使っているファイルで環境変数を使う場合は「NEXT_PUBLIC_ 」を先頭につける

“use client”

「You're importing a component that needs useEffect.」

と、出たときは "use client" をファイルの上部に記載 全部小文字

コンポーネントは一つのファイル内に複数作って良い

function MyButton() {
  return (
    <div>
      <button>MyButton Components!!</button>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <MyButton />
    </div>
  );
}

この例は Appがexportされるメインコンポーネントで、buttonはApp内で使うコンポーネント

<Link> タグ

aタグとの違いはリロード無しで移動

#idとhref

/about#id のような書き方で別ページの任意の場所(id)へ移動

<Link href={"/about#id"}>hoge</Link>

===
/aboutページ
<div id="id"></div>

三項演算子

よくつかう { 条件 ? trueの時 : falseの時 }

<li
            key={link.route}
            className={`${
              isActive && "text-primary-500"
            } flex-center p-medium-16 whitespace-nowrap`}
>
  • 意味:「isActiveなら文字を青く , そうでなければ undefinedが返ってくる」
  • {} の外は 普通のtailwindクラスなので条件式と関係ない
  • 3項演算の各要素はreturn内一番外のdivや<>と同様に、react fragmentが無いとエラーになる
return (
  condition ?
    <>
      <Component1 />
      <Component2 />
    </> :
    <Component3 />
);
  • <Component1 /> だけだと<>は必要ない

usePathname()

"use client";
import { usePathname } from "next/navigation";

const pathname = usePathname();

のようにして、現在のURLを取得する

  • pathnameをlogで見ると現在のルーティングが出る ex : /about

== 使用例:アクティブURLメニューの背景色を変える

const pathName = usePathname();
  return (
    <Link
      className={`${
        pathName === link.url && "bg-black text-white"
      }`}
      href={link.url}
    >
      {link.title}
    </Link>

useState snippet

useStateのひな型は snippet で出した方が早い

onClickなどはクライアントコンポーネント

Unhandled Runtime Error
Error: Event handlers cannot be passed to Client Component props.
  <... onClick={function} children=...>

ブラウザーでの操作(onClickやonScroll)は、 クライアントで行われる

上記のようなエラーは “use client” をつけると直る

useRouter()

const router = useRouter()

<AlertDialogAction onClick={() => router.push("/about")}>Continue</AlertDialogAction>

https://nextjs.org/docs/app/api-reference/functions/use-router

注意:import は import { useRouter } from "next/navigation"; からでないとエラーになる(×next/routerはpages用)

ページ「内」遷移 : useRef

useRefはreactのhooks

例 :

const ref = useRef()

  const handleClick =()=> {
    if(ref.current) {
      console.log(ref.current);
      ref.current.scrollIntoView({
        behavior: "smooth",
      })
    }
  }
===
<div ref={ref}>

</div>

ref.current を見ると、ref={ref} をつけたタグを取得できていることがわかる

  • scrollIntoView (JS) : https://developer.mozilla.org/ja/docs/Web/API/Element/scrollIntoView
  • ` ref.currentnull でない場合、条件文 if (ref.current)true と評価されます。なぜなら、useRef フックは初期値として null を返すため、ref.currentnull でない場合は、何らかの値がセットされていることになります。`

← Go home