問題、エラー
@toast-ui/react-editor
やEditor.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>
)
}