I can't seem to find a solution to this on any of the documentation. All I want is have a button toggle to switch between a light and dark mode.
It's not really necessary to install an additional npm package to achieve theme switching.
If all you want to achieve is having a toggle, you can list the desired themes in your tailwind.config.cjs
file like so:
plugins: [require('daisyui')],
daisyui: {
themes: ['light', 'dark'],
},
And then in your component, have a state, a toggle function and a useEffect that handles attribute injection into the HTML tag of the document (we want to have the global theme as an attribute in the html element as per the daisyUI docs: https://daisyui.com/docs/themes/)
function MyAwesomeThemeComponent() {
const [theme, setTheme] = React.useState('light');
const toggleTheme = () => {
setTheme(theme === 'dark' ? 'light' : 'dark');
};
// initially set the theme and "listen" for changes to apply them to the HTML tag
React.useEffect(() => {
document.querySelector('html').setAttribute('data-theme', theme);
}, [theme]);
return (
<label className="swap swap-rotate">
<input onClick={toggleTheme} type="checkbox" />
<div className="swap-on">DARKMODE</div>
<div className="swap-off">LIGHTMODE</div>
</label>
);
}