Blog>
Snippets

Using Sass Variables for Theming in Next.js

Provide an example of how to use Sass variables to manage themes (dark and light mode) in a Next.js application, including the definition and usage of color variables.
// Install Sass by running: npm install sass

// 1. Define Sass variables in a partial file (e.g., _variables.scss)
$light-theme-colors: (
  primary: #ffffff,
  secondary: #cccccc,
  background: #f7f7f7,
  text: #333333
);

$dark-theme-colors: (
  primary: #333333,
  secondary: #444444,
  background: #1a1a1a,
  text: #f7f7f7
);

// 2. Create a mixin to apply the theme
@mixin apply-theme($theme-colors) {
  --primary-color: map-get($theme-colors, primary);
  --secondary-color: map-get($theme-colors, secondary);
  --background-color: map-get($theme-colors, background);
  --text-color: map-get($theme-colors, text);
}

// 3. Use the mixin based on a class in your global styles file (e.g., globals.scss)
.light-theme {
  @include apply-theme($light-theme-colors);
}

.dark-theme {
  @include apply-theme($dark-theme-colors);
}
This piece of code shows how to set up Sass variables for two different themes (light and dark) and create a mixin to apply theme-based styles. _variables.scss is where color themes are defined using Sass maps. A mixin called apply-theme is created to make it convenient to apply a theme by mapping the color variables. The mixin is used in a global styles file, assigning different color values based on the provided theme context.
// 4. Toggle the theme in your Next.js pages or components
import { useEffect, useState } from 'react';
import '../styles/globals.scss';

export default function MyApp({ Component, pageProps }) {
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    document.body.className = theme === 'dark' ? 'dark-theme' : 'light-theme';
  }, [theme]);

  // Method to toggle the theme
  const toggleTheme = () => {
    setTheme(theme === 'light' ? 'dark' : 'light');
  };

  return (
    <>
      <button onClick={toggleTheme}>Toggle Theme</button>
      <Component {...pageProps} />
    </>
  );
}
This piece of code is an example of a Next.js component or page that uses the useState and useEffect hooks from React to manage and apply the theme class to the document body. The toggleTheme function changes the theme state between 'light' and 'dark', which triggers the useEffect hook to update the body class on theme state changes. A button is provided to demonstrate how a user could toggle the theme in the application.