'Next.js Error: Element type is invalid: expected a string - while trying to use Next.js with MUI
I'm trying to use Next.js with MUI v5 and in order to do so I had to make some configurations to remove server-side injected CSS and fix the resolution order. I used this tutorial and followed every step. but when I run the script yarn dev or npm run dev I face this error:
What should I do to fix this problem?
Here's my _document.js file:
import * as React from 'react'
import Document, { Html, Head, Main, NextScript } from 'next/document'
import createEmotionServer from '@emotion/server/create-instance'
import createEmotionCache from '../src/utility/createEmotionCache'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
MyDocument.getInitialProps = async (ctx) => {
const originalRenderPage = ctx.renderPage
const cache = createEmotionCache()
const { extractCriticalToChunks } = createEmotionServer(cache)
/* eslint-disable */
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) =>
function EnhanceApp(props) {
return <App emotionCache={cache} {...props} />
},
})
/* eslint-enable */
const initialProps = await Document.getInitialProps(ctx)
const emotionStyles = extractCriticalToChunks(initialProps.html)
const emotionStyleTags = emotionStyles.styles.map((style) => (
<style
data-emotion={`${style.key} ${style.ids.join(' ')}`}
key={style.key}
dangerouslySetInnerHTML={{ __html: style.css }}
/>
))
return {
...initialProps,
styles: [
...React.Children.toArray(initialProps.styles),
...emotionStyleTags,
],
}
}
And here's my package.json file:
{
"name": "testing-next-app",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@emotion/cache": "^11.7.1",
"@emotion/react": "^11.7.1",
"@emotion/server": "^11.4.0",
"@emotion/styled": "^11.6.0",
"@fontsource/roboto": "^4.5.2",
"@mui/icons-material": "^5.3.1",
"@mui/material": "^5.4.0",
"next": "12.0.10",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"eslint": "8.8.0",
"eslint-config-next": "12.0.10",
"prop-types": "^15.8.1"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
