🍡

開発日記-2024-01-26 / Next.jsのpathnameの取得

公開日
6か月前
2024-01-26
更新履歴

Next.jsのサーバーコンポーネントで pathname の取得が簡単にできるようになってた

npmのパッケージをインストールするだけでできる。

Terminal
pnpm add next-impl-getters
server
import { getPathname } from 'next-impl-getters/get-pathname'

export default function Component() {
    const pathname = getPathname()

    return (
        // ...
    )
}

以下のクライアントコンポーネントと同じ感じで取得できる。

client
'use client'

import { usePathname } from 'next/navigation'

export default function Component() {
    const pathname = usePathname()

    return (
        // ...
    )
}

VS Codeの便利な設定 Sticky Scroll の設定方法

スクロールしたときにメソッド名などが上部に固定されて便利。

settings.json
{
  "editor.stickyScroll.enabled": true,
  "editor.stickyScroll.maxLineCount": 5,
}

Reactでタグ名を指定できるコンポーネントの作り方

以下のコードで出力されるHTMLは <main>Hello.</main> になる。

import { PropsWithChildren } from 'react'

export interface ComponentProps extends PropsWithChildren {
  tagName?: keyof JSX.IntrinsicElements
}

export default function Component({ tagName, children }: ComponentProps) {
  const TagName = tagName ?? 'div' // TagName は大文字から始める必要がある
  return <TagName>{children}</TagName>
}

function Page() {
  return <Component tagName="main">Hello.</Component>
}

レトロゲーム風のフォント

ゲームを作るときに、このフォントを使ってみよう。