How to Intergrate Chakra UI in Next.js 🧑‍🎨
Tags: nextjs, chakra, javascript, typescript
Published: 2021-12-12 16:18:43


**I would like to preface this article, by saying that I wrote this content for [Creative Guru Designs](https://creativedesignsguru.com/blog/). Creative Guru Designs has many great NextJs blogs/examples, along with many other frontend/[SaaS](https://nextlessjs.com/) resources!**

Creating a user-interphase is never a simple task, but [Chakra UI](https://chakra-ui.com/) is a great UI library to get your Next.js application up and running fast, all while maintaining aesthetics. In this guide, you'll learn how to set up a simple Next.js app with Chakra UI. 

### Presequisites 

+ ✅  Standard knowledge of NextJS setup and usage
+ ✅  Some experience with UI/UX Design

### Create a NextJs Project

You can create a blank Next.js project by running:

```
npx create-next-app my-project
# or
yarn create next-app my-project
```
### Create a NextJs Project Using Typescript

Alternatively, Next.js provides an integrated TypeScript, similar to an IDE. You can create a TypeScript project with [<code>create-next-app</code>](https://nextjs.org/docs/api-reference/create-next-app) using the <code>--ts</code>, <code>--typescript</code> flag as shown below:

```
npx create-next-app@latest --ts
# or
yarn create next-app --typescript
```

🚨**Please note that when adding Chakra UI to a TypeScript project, a minimum TypeScript version of 4.1.0 is required.**

Once you've successfully created you're Typescript project, cd into the project directory and get started by creating an empty <code>tsconfig.json</code> file in the root folder:

```
touch tsconfig.json
```

*Next.js will automatically configure this file with default values. It is also supported to provide your own <code>tsconfig.json</code> with custom compiler options. To provide a relative path to a <code>tsconfig.json</code> file, set a <code>typescript.tsconfigPath prop</code> inside your <code>next.config.js</code> file.*

After creating your <code>tsconfig.json</code> file, run <code>next</code>, *normally npm run dev/yarn dev* and Next.js will direct you through the installation of the required packages to finish the application setup:

```
npm run dev

# You'll see instructions like these:
#
# Please install TypeScript, @types/react, and @types/node by running:
#
#         yarn add --dev typescript @types/react @types/node
#
# ...
```
Once all installations are successful and complete, you're ready to start converting files from <code>.js</code> to <code>.tsx</code> and coding in TypeScript!.

🚨**A file named <code>next-env.d</code>.ts will be created in the root of your project. This file ensures Next.js types are picked up by the TypeScript compiler. You cannot remove it or edit it as it can change at any time.**

Learn more about using Typescript with Node.js in their [Docs](https://nextjs.org/docs/basic-features/typescript).

### Adding Chakra UI to your Next.js Application 

To get started using Chakra UI, install the core Chakra UI package by running:

```
npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4
# or
yarn add @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4
```

After installation, you'll need to add [Chakra providers](https://chakra-ui.com/guides/with-nextjs#chakra-providers).

### Adding in Chakra Providers

Chakra uses the ChakraProvider component, which then wraps your website with a context containing properties such as the Chakra theme, color mode functionality, CSS reset, global styles, and more.

In <code>components/_app.js</code>:

```javascript
import { ChakraProvider, Heading } from "@chakra-ui/react"
import * as React from "react";
import { render } from "react-dom";
import "./styles.css";

function App() {
  return <Heading>Welcome to using Chakra + Next.Js</Heading>;
}

const rootElement = document.getElementById("root");
render(
  <ChakraProvider>
    <App />
  </ChakraProvider>,
  rootElement
);
```

If you are using Typescript, use the ChakraProvider component in <code>components/_app.tsx</code> like so:

```javascript
import { ChakraProvider, Heading } from "@chakra-ui/react";
import * as React from "react";
import { render } from "react-dom";
import "./styles.css";

function App() {
  return <Heading>Welcome to Chakra + TypeScript</Heading>;
}

const rootElement = document.getElementById("root");
render(
  <ChakraProvider>
    <App />
  </ChakraProvider>,
  rootElement
);
```

If everything was imported successfully, once the component rerenders you should be greeted with your newly written heading. 

<img src="https://i.imgur.com/EqGnKiB.png"></img>

Now that you're getting the hang of it, let's create a simple hero component! First create a <code>Hero.js</code> or <code>Hero.tsx</code> file. And inside try out the following example code:

```javascript
import {
  Container,
  Stack,
  Flex,
  Box,
  Heading,
  Text,
  Image,
  Icon,
  useColorModeValue,
  UnorderedList,
  ListItem
} from "@chakra-ui/react";

export const Blob = (props) => {
  return (
    <Icon
      width={"100%"}
      viewBox="0 0 578 440"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      <path
        fillRule="evenodd"
        clipRule="evenodd"
        d="M239.184 439.443c-55.13-5.419-110.241-21.365-151.074-58.767C42.307 338.722-7.478 282.729.938 221.217c8.433-61.644 78.896-91.048 126.871-130.712 34.337-28.388 70.198-51.348 112.004-66.78C282.34 8.024 325.382-3.369 370.518.904c54.019 5.115 112.774 10.886 150.881 49.482 39.916 40.427 49.421 100.753 53.385 157.402 4.13 59.015 11.255 128.44-30.444 170.44-41.383 41.683-111.6 19.106-169.213 30.663-46.68 9.364-88.56 35.21-135.943 30.551z"
        fill="currentColor"
      />
    </Icon>
  );
};

export default function Hero() {
  return (
    <Container maxW={"7xl"}>
      <Stack
        align={"center"}
        spacing={{ base: 8, md: 10 }}
        py={{ base: 20, md: 28 }}
        direction={{ base: "column", md: "row" }}
      >
        <Stack flex={1} spacing={{ base: 5, md: 10 }}>
          <Heading
            lineHeight={1.1}
            fontWeight={600}
            fontSize={{ base: "3xl", sm: "4xl", lg: "6xl" }}
          >
            <Text
              as={"span"}
              position={"relative"}
              _after={{
                content: "''",
                width: "full",
                height: "30%",
                position: "absolute",
                bottom: 1,
                left: 0,
                bg: "blue.400",
                zIndex: -1
              }}
            >
              Example Application
            </Text>
            <br />
            <Text as={"span"} color={"blue.400"}>
              Next.js + Chakra UI
            </Text>
          </Heading>
          <Flex justifyContent="center" textAlign="left">
            <UnorderedList>
              <ListItem>Uses Next.js/Typescript on Front-end.</ListItem>
              <ListItem>Uses ChakraUI for UI.</ListItem>
            </UnorderedList>
          </Flex>
        </Stack>
        <Flex
          flex={1}
          justify={"center"}
          align={"center"}
          position={"relative"}
          w={"full"}
        >
          <Blob
            w={"150%"}
            h={"150%"}
            position={"absolute"}
            top={"-20%"}
            left={0}
            zIndex={-1}
            color={useColorModeValue("blue.50", "blue.400")}
          />
          <Box
            position={"relative"}
            height={"300px"}
            rounded={"2xl"}
            boxShadow={"2xl"}
            width={"full"}
            overflow={"hidden"}
          >
            <Image
              alt={"Hero Image"}
              fit={"cover"}
              align={"center"}
              w={"100%"}
              h={"100%"}
              src={
                "https://media.istockphoto.com/photos/ink-blue-color-paint-pouring-in-water-isolated-on-white-background-picture-id902957562?k=20&m=902957562&s=612x612&w=0&h=y_Nu9PuNq9vhnQLBgjQ9jhuSW7y9vj62WP33D8d_Z9A="
              }
            />
          </Box>
        </Flex>
      </Stack>
    </Container>
  );
}
```
Once you've created your hero component, import it into your <code>components/_app.js</code> or <code>components/_app.tsx</code> file like so:

```javascript
import { ChakraProvider, Heading } from "@chakra-ui/react";
import * as React from "react";
import { render } from "react-dom";
import "./styles.css";
import Hero from "./hero.tsx";

function App() {
  return (
    <div>
      <Hero />
    </div>
  );
}

const rootElement = document.getElementById("root");
render(
  <ChakraProvider>
    <App />
  </ChakraProvider>,
  rootElement
);
```

Once your application re-renders, your landing page should resemble the following:

<img src="https://i.imgur.com/sXdaxVr.png">

Congratulations! You can now create awesome user interphases in half the time, all thanks to Chakra UI. 🎉