In this lesson, we will learn how to set up and use Chakra UI with Next.js.
We'll use Chakra UI to customize the way Next.js styles every page in our application by defining a _app.tsx
file. We'll wrap our app in the ThemeProvider
that Chakra gives us as well as use CSSReset
to reset the default browser styling.
After this initial set up, you'll see how easy it is to start styling pages with Chakra by using components like Heading
, Link
, and Flex
exposed from the core package.
Instructor: [0:00] First, let's install the package with yarn add @chakra-ui/core. Because chakra-ui is built upon emotion, we also install emotion instead of styles components to write custom styles and themes later. Then, let's create a special file in the pages directory called _app.tsx.
[0:27] This file will allow us to customize the way Next.js initializes every single page. Now, in this file we'll import ThemeProvider and CSSReset from @chakra-ui/core. Then we'll have an app component that's going to be exported.
[0:46] We'll grab the components and pageProps from the props this app component receives which are going to be the original page components and their props that we want to wrap around. We return everything wrapped inside the ThemeProvider and resets the browser CSS with the CSSReset component.
[1:09] Now, let's restart the dev server. Let's go back to a page in our project and import Heading from @chakra-ui. Then we can replace the vanilla h1 tag into heading as h1 to tell @chakra-ui to render the components as an h1 tag and size set to 2xL to make it extra-large.
[1:37] Notice that we get auto-suggestion for most of the props in @chakra-ui which is very nice. Then let's use the Link component from @chakra-ui for Link. Because there's a naming conflict, let's just rename the Next.js link to NextLink. We can wrap the text of the Link inside the @chakra-ui Link.
[2:03] We'll need to enable the passHref prop on the next Link so that we can still have the URL preview on the lower-left corner in browsers. Finally, we can wrap everything in a Flex component which is basically a Flex box dev and sets the flexDirection to column and alignItems to center. We can also add some margins to make it look better.