LoginSignup
0
0

More than 3 years have passed since last update.

Gatsby.js 【error "window" is not available during server side rendering.】

Posted at

Gatsby.jsにて、

error "window" is not available during server side rendering.

上記のエラー時の対処法になります。

サーバーサイドレンダリング(SSR)でwindowオブジェクトを取得している為のエラー


import React from 'react'

export default () => {
  const loc = window.location.pathname //windowオブジェクト
  return (
    <div>
     <p>{loc}</p>
    </div>
  )
}

上記のように、windowオブジェクトを使用しているとbuild時にエラーになります。

useState, useEffectを使うことで解決

import React, { useState, useEffect } from 'react'

export default () => {
  const [loc, setLocationName] = useState('')
  useEffect(() => {
    setLocationName(window.location.pathname)
  }, [])

  return (
    <div>
     <p>{loc}</p>
    </div>
  )
}

useState, useEffectを使うことで、クライアントサイドで呼び出すことができるので、
error "window" is not available during server side rendering.を解消できました。

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