Create a theme toggle with Tailwind Css and next-themes

22 January, 2022

2 min read

I was used to styled-components. To be honest, I never used synthetic sugar CSS frameworks. That's why I took the challenge and started building my blogfolio site with NextJs and Tailwind Css.

I really love how Tailwind Css and next-themes work with each other.

Next-Themes Settings

You can read more about next-themes here.

pages/_app.js
import '../styles/globals.css';

import { ThemeProvider } from 'next-themes';

function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider attribute="class">
      <Component {...pageProps} />
    </ThemeProvider>
  );
}

export default MyApp;

Tailwind Css Configuration

We have to use darkMode: 'class'. There are two options, though.

  1. media: It works with media queries.

  2. class: It works with the class name called dark. By default this uses the prefers-color-scheme CSS media feature, but you can also build sites that support toggling dark mode manually using the class strategy.

tailwind.config.js
const { spacing, fontFamily } = require('tailwindcss/defaultTheme');

module.exports = {
  mode: 'jit',
  content: ['./pages/**/*.js', './components/**/*.js', './layouts/**/*.js'],
  darkMode: 'class',
  variants: {
    typography: ['dark']
  },
  plugins: [require('@tailwindcss/typography')]
};

Final Component

Here is the code for the toggle animation component. I used lil bit sugar using a sound effect.

components/Switch.js
import { useState, useEffect } from 'react';
import { useTheme } from 'next-themes';
import useSound from 'use-sound';

export default function Switch() {
  const [mounted, setMounted] = useState(false);
  const { resolvedTheme, setTheme } = useTheme();
  const [play] = useSound('/static/audio/toggle.mp3');

  // Theme is available after mounted
  useEffect(() => setMounted(true), []);

  function onToggle() {
    setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
    play();
  }

  return (
    <button
      type="button"
      onClick={onToggle}
      aria-label="Dark Mode Toggle"
      className="grid items-center justify-center"
    >
      <div className="relative inline-block h-[30px] w-[48px]">
        {mounted && (
          <span className="switch-transition before:switch-transition absolute top-0 left-0 bottom-0 right-0 cursor-pointer rounded-[30px] bg-bgDark before:absolute before:left-[2px] before:bottom-[2px] before:h-[26px] before:w-[26px] before:rounded-full before:bg-white before:content-[''] dark:bg-gray-400 dark:before:translate-x-[18px] dark:before:bg-gray-200" />
        )}
      </div>
    </button>
  );
}

Conclusion

Copy and paste this code and start enjoying your own dark theme toggle animation. Good bye! See yah!

Newsletter

Subscribe to get exclusive updates and tech recipes inspiration in your inbox from the chef. I also publish semi-regular newsletters containing links to interesting articles about design, technology, and startups.

Unsubscribe at any time. Powered by Revue.