0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Next.js] Dynamic Import を使用してSSRを回避する

Last updated at Posted at 2024-11-27

問題、エラー

@toast-ui/react-editorEditor.jsなどSSRを支援していないライブラリーを利用すると以下のエラーが発生します。

 ⨯ ReferenceError: Element is not defined

原因

Next.js公式ドキュメント

With no SSR

To dynamically load a component on the client side, you can use the ssr option to disable server-rendering. This is useful if an external dependency or component relies on browser APIs like window.

import dynamic from 'next/dynamic'

const DynamicHeader = dynamic(() => import('../components/header'),
 {  ssr: false,})
  • Next.jsは基本的に各ページをpre-renderingする
  • サーバーサイドからwindowみたいなブラウザーAPIを利用しているライブラリーやコンポーネントをpre-renderingしようとするからエラーが発生

対応

ダイナミックインポート(Dynamic Inport)を利用してインポートの際に、{ssr: false} を第二引数に渡すとSSRされず、React単体のようにクライアントでのみレンダリングされます。

import dynamic from 'next/dynamic'
 
const Sample = dynamic(
  () => import('../components/Sample'),
  {
    ssr: false,
  }
)
 
export default function Page() {
  return (
    <div>
      <Sample />
    </div>
  )
}

参照

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?