Back

Jan 9, 2023

Jan 9, 2023

Learn How to Utilize Chakra UI’s Color Mode in Your Next.Js Application

Let's learn how to use Chakra UI to create a cohesive user experience in your next Next.js project. It's a super useful library for web developers.

decorative cover image showing a web developer working with Next.Js
decorative cover image showing a web developer working with Next.Js
decorative cover image showing a web developer working with Next.Js

Next.js is a React framework that optimizes your application, speeding up the development and production phases. It provides server-side rendering, search engine optimization, and a variety of other unique capabilities in your web application. On their official website, you can learn more about what Next.js has to offer.

Styles can help you create amazing layouts and a distinctive user experience for your web application. This allows easier navigation within the application. In this article, we'll look at how to use one of the various style frameworks and libraries available to create a customized theme.

What is Chakra UI?

Chakra UI is a basic component-level-based React library. It features a number of components that are adaptable and simple to utilize in your application. When developing the user experience of a web application, Chakra UI speeds up the development process.

Getting Started

To successfully create a Next.js application, use the following command:

npx create-next-app

Save this code

Install Dependencies

Following that, we'll look at how to add the Chakra UI library to a Next.Js application. We’ll use one of the instructions provided in the code blocks below:

yarn add @chakra-ui/react @chakra-ui/icons @emotion/react@^11 @emotion/styled@^11 framer-motion@^6

Save this code

or

npm i @chakra-ui/react @chakra-ui/icons @emotion/react@^11 @emotion/styled@^11 framer-motion@^6

Save this code

The instructions in the code block above will be used to configure Chakra UI in our Next.js application.

Chakra UI Set up

To utilize Chakra UI in your Next.js application, add the following code block to /pages/_app.js to import ChakraProvider at the root of your application:

import { ChakraProvider } from '@chakra-ui/react'
function MyApp({ Component, pageProps }) {
  return (
  )
}
export default MyApp

Save this code

Styling a Next.js app With Chakra UI

By leveraging the capabilities the library offers, Chakra UI makes it extremely simple to style components in your Next.js application. We’ll import components from Chakra UI and style them using the code block below in /pages/index.js:

import { Container, Box } from '@chakra-ui/react'
import Head from "next/head";
export default function Home() {
 return (
          This is the Box
 );
}

Save this code

The Container and Box components were imported from @chakra-ui/react as seen in the code block above. The Box component is utilizing the style props that Chakra UI provides. We used the following props: bg (short for background), w (short for width), and p (short for padding).

chakra user interface showing a container and a box

Color Mode in Next.js

By default, the Chakra UI Color Mode feature allows you to alter the color mode in your application. We can utilize the functionality to theme our application to specify the color we want to appear in dark mode, light Mode, or system theme for our layout or components.

The following code block will be pasted into the newly created file /styles/theme.js:

import { extendTheme } from "@chakra-ui/react";
export const theme = extendTheme({
  initialColorMode: "dark",
  useSystemColorMode: false,
});
export default theme;

Save this code

From the code block above, we imported extendTheme, which accepts an object used to quickly override or modify the Chakra UI theme. The initialColorMode, which can be adjusted to dark, light, or system, allows us to choose the theme of our application. Additionally, useSystemColorMode accepts a boolean value, allowing use of the system’s theme.

To utilize theme.js, we’ll create a new component, /pages/_document.js, and insert the following code block into it:

import { ColorModeScript } from '@chakra-ui/react'
import NextDocument, { Html, Head, Main, NextScript } from 'next/document'
import theme from '../styles/theme'
export default class Document extends NextDocument {
  render() {
    return (
    )
  }
}

Save this code

The code block above shows ColorModeScript, which accepts a prop initialColorMode. This allows us to toggle between light and dark themes with ease.

Next, we’ll modify /pages/index.js to use the useColorMode hook, which gives access to the current color mode. To use it, add the following code block:

import { Container, Box, Button, useColorMode } from '@chakra-ui/react'
import Head from "next/head";
export default function Home() {
const { colorMode, toggleColorMode } = useColorMode();
 return (
          {colorMode === "light" ? "Dark mode": "Light mode"}
          This is the Box
 );
}

Save this code

Charkra UI light more dark mode toggle

Toggling on darkMode and lightMode

Custom Styles with Chakra UI

In this section, we'll look at how to create custom styles for the Chakra UI components. This will allow us to control which colors appear when we switch between light and dark modes. Moving on, we will modify theme.js to add custom colors to our application:

export const theme = extendTheme({
  initialColorMode: "dark",
  useSystemColorMode: false,
  colors: {
    primary: {
      dark: "#003100",
      light: "#e6f6e6",
    },
    secondary: "#009400",
    text: {
      dark: "#000",
      light: "#fff"
     },
    icon: '#ffd700',
  },
});

Save this code

We now have custom colors of primary and secondary with dark and light color values in the code block above.

After that, we'll design unique styles for the Text and Button components. The mode function in Chakra UI accepts two arguments for dark and light modes.

Moving forward, we’ll now create /styles/ButtonStyles.js using the code block below:

import { mode } from "@chakra-ui/theme-tools";
export const ButtonStyle = {
  baseStyle: {},
  sizes: {},
  variants: {
    primary: (props) => ({
      color: mode("text.light", "white")(props),
      bg: mode("primary.dark", "secondary")(props),
    }),
  },
  defaultProps: {},
};

Save this code

Also, we will create /styles/TextStyles.js:

import { mode } from "@chakra-ui/theme-tools";
export const TextStyle = {
  baseStyle: {},
  sizes: {},
  variants: {
    primary: (props) => ({
      color: mode("text.dark", "text.light")(props),
    }),
  },
  defaultProps: {},
};

Save this code

The variants object takes in a primary function with a prop that indicates whether the current color mode is dark or light, and the function also returns an object from the above code block. We then utilize the mode function provided by Chakra UI to define what color appears when we flip between dark and light modes.

To utilize the custom component styles from the preceding code blocks, we’ll import them into theme.js and apply the styles to the components object in the following code block:

...
import { TextStyle as Text } from "./TextStyles";
import { ButtonStyle as Button } from "./ButtonStyles";
...
 components: {
    Text,
    Button,
  },
...

Save this code

Customize a Component Using useColorModeValue

The useColorModeValue hook accepts two arguments: the light mode value and the dark mode value. It is used to switch between styles based on the color mode. Using the code block below, we will import the hook and modify index.js:

...
const bg = useColorModeValue("primary.light", "primary.dark");
...
...
 This is the Box

Save this code

Chakra UI Theme Using Color Mode

In this section, we’ll theme our application using the custom styles we created. Next, /pages/index.js will be modified:

import {
  Box,
  Button,
  Container,
  Text,
  useColorMode,
  useColorModeValue,
} from "@chakra-ui/react";
import Head from "next/head";
import { MoonIcon, SunIcon } from "@chakra-ui/icons";
export default function Home() {
  const { colorMode, toggleColorMode } = useColorMode();
  const bg = useColorModeValue("primary.light", "primary.dark");
  return (
    
      h="100vh"
      display="flex"
      justifyContent="center"
      alignItems="center"
      maxW='container.sm'
    >
          {colorMode === "light" ?  : }        
        
          bg={bg}
          w="100%"
          p={4}
          display="flex"
          mt="4"
          alignItems="center"
          cursor="pointer"
          borderLeft="6px solid"
          borderColor="secondary"
          borderRadius="5px"
          boxShadow='dark-lg'
        >
            Chakra-UI Color mode in Next.Js
            😀 open
  );
}

Save this code

For the aim of switching between light mode and dark mode, the useColorModeValue hook and the custom component styles are used in the code block above.

web page showing chakra ui custom styles in action

Fully themed app

Conclusion

This article explored how to style a Next.js application using Chakra UI, and how to create custom styles for the components the library offers. In addition, we used the Chakra UI color mode feature to create custom themes using the extendTheme function. To learn more about the library, visit the official documentation of Chakra UI. Also, you can get all of the code for this article on my GitHub repository. Visit chakra-ui-color-mode to test out the live version.

Written by

Written by

Clarence Bakosi

Clarence Bakosi

SHARE

SHARE

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.