In this section we will see how to use chakra ui in nextjs 13. For this section we will use next 13 with typescript.
Create Next.JS 13 App
Chose below command to create next js app.
npx create-next[email protected]
# or
yarn create next-app
# or
npx create-next[email protected] --typescript
# or
yarn create next-app --typescript
Note: Next.js 13 introduces a new app/ directory / folder structure. By default it uses Server Components. To use Chakra UI in those components, you need to convert them into client-side component by adding a 'use client'; at the top of your file. Chakra UI only works in client-side components.
If you're not using the new app/ directory, there's no need to add the 'use client'; directive.
Install Chakra UI in Next.JS
Run below command to install chakra ui in nextjs
npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
# or
yarn add @chakra-ui/react @emotion/react @emotion/styled framer-motion
After installing Chakra UI, you need to set up the ChakraProvider at the root of your application.
Go to pages/_app.js or pages/_app.tsx (create it if it doesn't exist) and wrap the Component with the ChakraProvider:
// pages/_app.js
import { ChakraProvider } from '@chakra-ui/react'
function MyApp({ Component, pageProps }) {
return (
<ChakraProvider>
<Component {...pageProps} />
</ChakraProvider>
)
}
export default MyApp
In nextjs with typescript project.
_app.tsx
import type { AppProps } from "next/app";
import { ChakraProvider } from "@chakra-ui/react";
export default function App({ Component, pageProps }: AppProps) {
return (
<ChakraProvider>
<Component {...pageProps} />
</ChakraProvider>
);
}
Now Test Chakra UI components.
import Head from "next/head";
import { Heading, Flex } from "@chakra-ui/react";
export default function Home() {
return (
<>
<Head>
<title>Next App with Chakra UI</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<Flex height="100vh" alignItems="center" justifyContent="center">
<Heading>Install Chakra UI In NextJS 13</Heading>
</Flex>
</main>
</>
);
}