I just created a next.js 13 typescript application using npx create-next-app
. I've removed all sample css and html and tried bringing in MUI. My app/layout.tsx
looks like this:
import { CssBaseline } from '@mui/material'; export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <CssBaseline /> {children} </body> </html> ) }
Adding the CSSBaseline
bit will produce a bunch of errors about things missing from the React import. Read online This is because React is accessed from a server component, and the root layout component must be that server component. This is the error output:
Server Error TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component This error happened while generating the page. Any console logs will be displayed in the terminal window. Call Stack React node_modules/@emotion/react/dist/emotion-element-6bdfffb2.esm.js (14:41) (sc_server)/./node_modules/@emotion/react/dist/emotion-element-6bdfffb2.esm.js file:///[...]/.next/server/app/page.js (1724:1) __webpack_require__ file:///[...]/.next/server/webpack-runtime.js (33:42) eval webpack-internal:///(sc_server)/./node_modules/@emotion/styled/base/dist/emotion-styled-base.esm.js (8:72) (sc_server)/./node_modules/@emotion/styled/base/dist/emotion-styled-base.esm.js file:///[...]/.next/server/app/page.js (1768:1) __webpack_require__ file:///[...]/.next/server/webpack-runtime.js (33:42) eval webpack-internal:///(sc_server)/./node_modules/@emotion/styled/dist/emotion-styled.esm.js (5:95) (sc_server)/./node_modules/@emotion/styled/dist/emotion-styled.esm.js file:///[...]/.next/server/app/page.js (1779:1) __webpack_require__ file:///[...]/.next/server/webpack-runtime.js (33:42) require node_modules/@mui/styled-engine/node/index.js (46:37)
Shouldn't I do this? What did I miss?
I feel like once I get this done, the rest of the things will fall into place and I'll be able to build my MUI app.
I'm considering porting the material-next-ts example from page router to application router. But the version of emotion being used supports the simpler default method, which seems to require zero setup, so all the hoops the page routing jumps through in the example appear to be unnecessary. It would be great if the example was ported to Application Router!
The guidance in the error message will resolve the issue:
Try adding the
'use client'
directive to the top ofapp/layout.tsx
. The following is an explanation from the Next.js documentation on why'Use client'
is necessary: Here is another part explanation Your
app/layout.tsx
is a server component by default: