I need to integrate the dark mode into my project. I use NextJs v12.1.3, react 18.1.0 and tailwindcss v3.1.2. I tried this guide on the official site, but the manual selection doesn't work for me. It always shows the operating system's theme.
For example if I want to force the theme to be light I do this:
<html className="light">
<body className="h-10 w-10">
<div className="bg-white flex w-10 h-10 dark:bg-black"></div>
</body>
</html>
This shows always the OS' theme. I also added this to force it:
// On page load or when changing themes, best to add inline in `head` to avoid FOUC
if (
localStorage.theme === 'dark' ||
(!('theme' in localStorage) &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
// Whenever the user explicitly chooses light mode
localStorage.theme = 'light';
I also did this into the _document.tsx
file:
<Html className="light">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
I also set up darkMode: 'class'
into the tailwind.config.js
file
This is my full tailwind.config.js
file
const colors = require('tailwindcss/colors');
module.exports = {
purge: [],
darkMode: 'class',
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
tailwindcss: {},
autoprefixer: {},
theme: {
colors: {
transparent: 'transparent',
current: 'currentColor',
black: '#212121',
white: colors.white,
gray: {
...colors.gray,
100: '#f0f2f5',
200: '#DADFE7',
300: '#a9b5c6',
400: '#6c809d',
500: '#647697',
600: '#5a6C87',
700: '#394556',
800: '#313B49',
900: '#181D25',
},
teal: {
50: '#ECFDFA',
100: '#DAFCF6',
200: '#B4F8ED',
300: '#8FF5E4',
400: '#6AF1DB',
500: '#47EED1',
600: '#15E0BE',
700: '#10A88F',
800: '#0A705F',
900: '#053830',
},
indigo: colors.indigo,
red: colors.rose,
yellow: colors.amber,
orange: {
...colors.orange,
300: '#ffce30',
700: '#d49100',
},
extend: {
transitionDuration: {
0: '0ms',
2000: '2000ms',
},
},
},
},
plugins: [require('@tailwindcss/forms'), require('@tailwindcss/typography')],
};
To be honest, I want only light mode at this moment, but I have some components styled also for dark mode and I don't want to restyle them because later I will need it.
What do you think I did wrong?
P.S. I don't want to use next-themes
to handle the dark/light mode.