😈
Error: Cannot read properties of undefined (reading 'Provider')の対処法
はじめに
Next.jsで開発している最中に、react-iconsを<IconContext.Provider>
でwrapして使用しようとすると、Error: Cannot read properties of undefined (reading 'Provider')
というエラーが発生しました。
このエラーの解決法について、調べてもあまり日本語記事がなかったので、備忘録も兼ねて記しておきます。
想定読者
- 過去の自分と同じように、このエラーで悩んでいる人
- react-iconsを使って開発している人
環境
依存関係たち
"dependencies": {
"clsx": "^2.1.0",
"next": "^14.1.3",
"react": "^18",
"react-dom": "^18",
"react-icons": "^5.0.1",
"sass": "^1.71.1"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10.0.1",
"eslint": "^8",
"eslint-config-next": "14.1.4",
"postcss": "^8",
"sass": "^1.71.1",
"tailwindcss": "^3.3.0",
"typescript": "^5"
}
エラーコード.tsx
<IconContext.Provider value={{ hoge: foo }}>
<HogeIcons /> {/* react-icons */}
</IconContext.Provider>
解決方法
修正後のコード.tsx
'use client'
<IconContext.Provider value={{ hoge: foo }}>
<HogeIcons /> {/* react-icons */}
</IconContext.Provider>
ファイルの先頭に'use client'
を追加し、クライアントコンポーネトにすることで解決できました。
また、SSR/RSCで使用する場合でも、react-iconsはクライアントコンポーネントでwrapする必要があるみたいです。
参考記事
Discussion