Dark/Light Mode

Stack components support light and dark mode out of the box. All UI components automatically adapt their colors, shadows, and contrast levels based on the selected theme.

You can switch between light and dark mode using next-themes (or any other library that changes the data-theme or class to dark or light attribute of the html element).

Here is an example of how to set up next-themes with Stack (find more details in the next-themes documentation):

  1. Install next-themes:
$npm install next-themes
  1. Add the ThemeProvider to your layout.tsx file:
1import { ThemeProvider } from 'next-themes'
2
3export default function Layout({ children }) {
4 return (
5 {/*
6 ThemeProvider enables theme switching throughout the application.
7 defaultTheme="system" uses the user's system preference as the default.
8 attribute="class" applies the theme by changing the class on the html element.
9 */}
10 <ThemeProvider defaultTheme="system" attribute="class">
11 {/* StackTheme ensures Stack components adapt to the current theme */}
12 <StackTheme>
13 {children}
14 </StackTheme>
15 </ThemeProvider>
16 )
17}
  1. Build a color mode switcher component:
1'use client';
2import { useTheme } from 'next-themes'
3
4export default function ColorModeSwitcher() {
5 // useTheme hook provides the current theme and a function to change it
6 const { theme, setTheme } = useTheme()
7
8 return (
9 <button
10 onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
11 aria-label="Toggle dark mode"
12 >
13 {/* Display different text based on current theme */}
14 {theme === 'light' ? 'Switch to dark mode' : 'Switch to light mode'}
15 </button>
16 )
17}

Now if you put the ColorModeSwitcher component in your app, you should be able to switch between light and dark mode. There should be no flickering or re-rendering of the page after reloading.