selbekk

Using Chakra UI with NextJS

July 22, 2020
2 min read

Want to use Chakra UI with NextJS? This article shows you how!

Lately I've been crushing hard on Segun Adebayo's UI framework Chakra UI. It gives you a very versatile palette of UI components that you can compose together and customize to create your very own look in no time. It's what I used to create Sjau with, for example!

Another great framework I love to work with is Next by my people over at Vercel. It makes it incredibly easy to create server-side rendered apps, and it's my go-to for creating production applications.

But how can I use my two favorite frameworks together? I didn't find a good resource for it the first time I did this, so here's my take on how to set this up.

Set up your app

If you're starting from scratch, Next provides us with a great scaffolding tool - create-next-app. Run it with npx create-next-app my-app, and let it do its magic.

Once it's done setting stuff up, you want to install the Chakra UI dependencies. Chakra unfortunately has a few dependencies you have to explicitly install, so if you're not feeling like visiting their great docs, feel free to copy the npm installs from here:

npm install @chakra-ui/core @emotion/core @emotion/styled emotion-theming

Apply Chakra to your _app!

The second step also happens to be the last step. Create a file in your pages directory called _app.js (or _app.tsx if you're into TypeScript), and apply the ThemeProvider and CSSReset components to make sure stuff works!

import React from "react";
import { AppProps } from "next/app";
import { ThemeProvider, CSSReset } from "@chakra-ui/core";

const App: React.FC<AppProps> = ({ Component, pageProps }) => {
  return (
    <ThemeProvider>
      <CSSReset />
      <Component {...pageProps} />
    </ThemeProvider>
  );
};

export default App;

And that's it! You now have a server-side rendered app, complete with critical CSS extraction, code splitting and all the niceties that is basically impossible to get right yourself without a framework.

Hope this helps you (and future me) get started with Chakra UI and NextJS.

All rights reserved © 2024