8

Dark Mode

Learn how to implement dark mode in your AxionJS application using next-themes.

Install next-themes

Start by installing next-themes:

npm install next-themes

AxionJS components are designed to work perfectly with next-themes using CSS variables for theming.

Create a theme provider

components/theme-provider.tsx
"use client"
 
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
 
export function ThemeProvider({
  children,
  ...props
}: React.ComponentProps<typeof NextThemesProvider>) {
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

Configure your layout

app/layout.tsx
import { ThemeProvider } from "@/components/theme-provider"
import "@/styles/globals.css"
import { Metadata } from "next"
 
export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
}
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head/>
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}

Add a mode toggle

Use this component to switch between light and dark modes:

components/mode-toggle.tsx
"use client"
 
import * as React from "react"
import { useTheme } from "next-themes"
 
export function ModeToggle() {
  const { theme, setTheme } = useTheme()
  const [mounted, setMounted] = React.useState(false)
 
  React.useEffect(() => {
    setMounted(true)
  }, [])
 
  if (!mounted) {
    return null
  }
 
  return (
    <button
      onClick={() => setTheme(theme === "light" ? "dark" : "light")}
      aria-label="Toggle Dark Mode"
    >
      {theme === "light" ? "Switch to Dark" : "Switch to Light"}
    </button>
  )
}

On this page