next-themes

Next themes library configuration for dark mode with tailwindcss

––– views

Installation

Library from next-themes

yarn add next-themes
bash

_app.js

import { ThemeProvider } from 'next-themes'; function MyApp({ Component, pageProps }) { return ( <ThemeProvider attribute='class' defaultTheme='system'> <Component {...pageProps} /> </ThemeProvider> ); } export default MyApp;
js

Set on button (Nav.jsx)

import { useTheme } from 'next-themes'; import { FiSun, FiMoon } from 'react-icons/fi'; export default function Nav() { const { theme, setTheme } = useTheme(); <button className='border-thin hover:border-accent-200 rounded-md p-2.5 hover:text-slate-700 focus:outline-none dark:hover:border-slate-500 dark:hover:text-slate-600' onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')} > {theme === 'light' ? <FiMoon size={20} /> : <FiSun size={20} />} </button>; }
jsx

tailwind.config.js

module.exports = { purge: ['./pages/**/*.{js,jsx,ts,tsx}', './components/**/*.{js,jsx,ts,tsx}'], darkMode: 'class', // or 'media' or 'class' };
js

To Add background image for dark mode & light mode

@layer components { .dark-mode { color: #ffffff; background: #171a23; background-attachment: fixed; transition: color 300ms, background-color 300ms; background-size: cover; background-image: url('url of image'); } .light-mode { color: #000; background: #ffffff; background-attachment: fixed; background-size: cover; transition: color 300ms, background-color 300ms; background-image: url('url of image'); } } html { @apply light-mode; } html.dark { @apply dark-mode; }
css