😊

Next.js export 実行時のタイムスタンプをコンポーネントで使う

2021/09/18に公開

next export を実行した時のタイムスタンプをレンダリングしたいときの方法です。
jsx 上で <span>{new Date()}</span> などとするとクライアントサイドでレンダリングされた時間が表示されてしまいます。

SSR 時のデータを React で使いたい場合は NextPage コンポーネント で Component.getInitialProps を使うと渡すことが出来ます。
(/pages 直下で export するコンポーネント)

コード

import { createContext } from 'react'

type InitialProps = { buildTime: string }
const IndexPage: NextPage<InitialProps> = ({ buildTime }) => (
  <div>
    <span>ビルド日時: {buildTime}</span>
  </div>
)

IndexPage.getInitialProps = async () => {
  return { buildTime: String(new Date()) }
}

export default IndexPage

useContext 経由で使う場合

import { createContext } from 'react'
export const TimeContext = createContext('')

type InitialProps = { buildTime: string }

const IndexPage: NextPage<InitialProps> = ({ buildTime }) => (
  <TimeContext.Provider value={buildTime}>
    <Index />
  </TimeContext.Provider>
)

IndexPage.getInitialProps = async () => {
  return { buildTime: String(new Date()) }
}

export default IndexPage
const Footer = () => {
  const timeStr = useContext(TimeContext)

  return <span>ビルド日時: {timeStr}</span>
}
GitHubで編集を提案

Discussion