Using Chakra UI in Next.js (Pages)
A guide for installing Chakra UI with Next.js pages directory
Templates
Use one of the following templates to get started quickly. The templates are configured correctly to use Chakra UI.
Installation
The minimum node version required is Node.20.x
Install dependencies
npm i @chakra-ui/react @emotion/reactAdd snippets
Snippets are pre-built components that you can use to build your UI faster.
Using the @chakra-ui/cli you can add snippets to your project.
npx @chakra-ui/cli snippet addUpdate tsconfig
If you're using TypeScript, you need to update the compilerOptions in the
tsconfig file to include the following options:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"skipLibCheck": true,
"paths": {
"@/*": ["./src/*"]
}
}
}If you're using JavaScript, create a jsconfig.json file and add the above
code to the file.
Setup provider
Wrap your application with the Provider component at the root of your
application.
This provider composes the following:
ChakraProviderfrom@chakra-ui/reactfor the styling systemThemeProviderfromnext-themesfor color mode
pages/_app.tsx
import { Provider } from "@/components/ui/provider"
export default function App({ Component, pageProps }: AppProps) {
return (
<Provider>
<Component {...pageProps} />
</Provider>
)
}In the pages/_document.tsx file, add the suppressHydrationWarning prop to
the html element.
pages/_document.tsx
import { Head, Html, Main, NextScript } from "next/document"
export default function Document() {
return (
<Html suppressHydrationWarning>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}Optimize Bundle
We recommend using the experimental.optimizePackageImports feature in Next.js
to optimize your bundle size by loading only the modules that you are actually
using.
next.config.mjs
export default {
experimental: {
optimizePackageImports: ["@chakra-ui/react"],
},
}This also helps resolve warnings like:
[webpack.cache.PackFileCacheStrategy] Serializing big strings (xxxkiB)Hydration errors
If you see an error like this: Hydration failed because the initial server rendered HTML did not match the client, and the error looks similar to:
+<div className="chakra-xxx">
-<style data-emotion="css-global xxx" data-s="">This is caused by how Next.js hydrates Emotion CSS in --turbo mode. Please
remove the --turbo flag from your dev script in your package.json file.
- "dev": "next dev --turbo"
+ "dev": "next dev"When this is fixed by the Next.js team, we'll update this guide.
Enjoy!
With the power of the snippets and the primitive components from Chakra UI, you can build your UI faster.
import { Button, HStack } from "@chakra-ui/react"
const Demo = () => {
return (
<HStack>
<Button>Click me</Button>
<Button>Click me</Button>
</HStack>
)
}