34
loading...
This website collects cookies to deliver better user experience
dark:
prefix. In the example below I basically write 2 styles (classes) for light/dark variants.<div class="bg-white dark:bg-black">
<h1 class="text-black dark:text-white">Hello World</h1>
</div>
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground: white;
--background: black;
}
[data-theme="light"] {
--background: white;
--foreground: black;
}
module.exports = {
mode: "jit",
purge: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
theme: {
colors: {
foreground: "var(--foreground)",
background: "var(--background)"
}
},
variants: {
extend: {}
},
plugins: []
};
index.jsx
,export default function Home() {
return (
<div className='h-screen w-full bg-background flex flex-col justify-center items-center space-y-4'>
<h1 className='text-foreground text-2xl font-bold'>Hello World</h1>
</div>
);
}
yarn dev
and see you should be able to see "Hello World".But how do we toggle themes? Here we lose tailwind's method to toggle theme but don't worry there's a simple solution.next-themes
by @Paco . The package by default modifies the data-theme attribute on the html element, which is exactly what we want.<ThemeProvider />
and use the theme hooks provided by the package to toggle our theme.import '../theme.css';
import { ThemeProvider } from 'next-themes';
const App = ({ Component, pageProps }) => (
<ThemeProvider>
<Component {...pageProps} />
</ThemeProvider>
);
export default App;
import { useTheme } from 'next-themes';
import React, { useState, useEffect } from 'react';
export default function Home() {
const [mounted, setMounted] = useState(false);
const { resolvedTheme, setTheme } = useTheme();
// After mounting, we have access to the theme
useEffect(() => setMounted(true), []);
return (
<div className='h-screen w-full bg-background flex flex-col justify-center items-center space-y-4'>
<h1 className='text-foreground text-2xl font-bold'>Hello World</h1>
<button
role='button'
onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}
className='outline:none bg-foreground text-background px-4 py-2 rounded-lg focus:ring'
>
{mounted && resolvedTheme === 'light' ? 'Dark Mode' : 'Light Mode'}
</button>
</div>
);
}
A quick favor: was anything I wrote incorrect or misspelled, or do you still have questions? Feel free to message me on twitter.