Using Chakra UI in Next.js (App)
A guide for installing Chakra UI with Next.js app directory
Templates
Use one of the following templates to get started quickly. The templates are configured correctly to use Chakra UI.
Installation
Install dependencies
npm i @chakra-ui/react@next @emotion/react
Add 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@next snippet add
Setup provider
Wrap your application with the Provider
component generated in the
components/ui/provider
component at the root of your application.
This provider composes the following:
ChakraProvider
from@chakra-ui/react
for the styling systemThemeProvider
fromnext-themes
for color mode
app/layout.tsx
import { Provider } from "@/components/ui/provider"
export default function RootLayout(props: { children: React.ReactNode }) {
const { children } = props
return (
<html suppressHydrationWarning>
<body>
<Provider>{children}</Provider>
</body>
</html>
)
}
Update tsconfig
If you're using TypeScript, you need to update the compilerOptions
in the
tsconfig file to include the following options:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Bundler",
"skipLibCheck": true,
"paths": {
"@/*": ["./src/*"]
}
}
}
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 to resolve warnings like:
[webpack.cache.PackFileCacheStrategy] Serializing big strings (xxxkiB)
Enjoy!
With the power of the snippets and the primitive components from Chakra UI, you can build your UI faster.
import { Button } from "@/components/ui/button"
import { HStack } from "@chakra-ui/react"
const Demo = () => {
return (
<HStack>
<Button>Click me</Button>
<Button>Click me</Button>
</HStack>
)
}