DEV Community

Maxine
Maxine

Posted on

How to Intergrate Chakra UI in Next.js πŸ§‘β€πŸŽ¨

I would like to preface this article, by saying that I wrote this content for Creative Guru Designs. Creative Guru Designs has many great NextJs blogs/examples, along with many other frontend/SaaS resources!

Creating a user-interphase is never a simple task, but Chakra UI 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
Enter fullscreen mode Exit fullscreen mode

Create a NextJs Project Using Typescript

Alternatively, Next.js provides an integrated TypeScript, similar to an IDE. You can create a TypeScript project with create-next-app using the --ts, --typescript flag as shown below:

npx create-next-app@latest --ts
# or
yarn create next-app --typescript
Enter fullscreen mode Exit fullscreen mode

🚨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 tsconfig.json file in the root folder:

touch tsconfig.json
Enter fullscreen mode Exit fullscreen mode

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

After creating your tsconfig.json file, run next, 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
#
# ...
Enter fullscreen mode Exit fullscreen mode

Once all installations are successful and complete, you're ready to start converting files from .js to .tsx and coding in TypeScript!.

🚨A file named next-env.d.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.

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
Enter fullscreen mode Exit fullscreen mode

After installation, you'll need to add 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 components/_app.js:

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
);
Enter fullscreen mode Exit fullscreen mode

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

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
);
Enter fullscreen mode Exit fullscreen mode

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

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

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Once you've created your hero component, import it into your components/_app.js or components/_app.tsx file like so:

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
);
Enter fullscreen mode Exit fullscreen mode

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

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

Top comments (7)

Collapse
 
kenkirito profile image
lakshya Mishra

Hi can you give source code my _app.tsx not working currectly

Collapse
 
maxinejs profile image
Maxine

There is currently no repo for this, what is your error?

Collapse
 
kenkirito profile image
lakshya Mishra

Got it was doing a silly mistake thank you

Thread Thread
 
maxinejs profile image
Maxine

Glad you got it :)

Collapse
 
stevereid profile image
Steve Reid • Edited

I'm confused by your implementation of the Chakra providers as I can't work out where you're passing through the Component and pageProps?

Collapse
 
maxinejs profile image
Maxine

which component are you referring to? if you are referring to the Chakra Provider component, it is being imported with the code:

import { ChakraProvider, Heading } from "@chakra-ui/react";
Enter fullscreen mode Exit fullscreen mode

You can look at the documentation for that also here:

chakra-ui.com/docs/getting-started

Could you specify what you meant more about not understanding the pageProps?

Collapse
 
saadahmad94 profile image
saadahmad94

GREAT..!!!