-
|
change dark mode by class only work after page init,.but not work after change route.html or body 's class will be auto reset after change page const useThemeListener = () => {
const { isDarkTheme } = useColorMode();
useEffect(() => {
const html = document.documentElement;
if (isDarkTheme) {
html.classList.add('tw-dark');
// setAtrribute data is work fine
document.body.setAttribute('arco-theme', 'dark');
} else {
html.classList.remove('tw-dark');
document.body.removeAttribute('arco-theme');
}
return () => {
html.classList.remove('tw-dark');
document.body.removeAttribute('arco-theme');
};
}, [isDarkTheme]);
};
const DarkModeMonitor: FC = ({ children }) => {
useThemeListener();
return <>{children}</>;
};
const Layout: FC<Props> = (props) => {
const { children, wrapperClassName, pageClassName } = props;
useKeyboardNavigation();
return (
<LayoutProviders>
<DarkModeMonitor>
<LayoutHead {...props} />
<SkipToContent />
<AnnouncementBar />
<Navbar />
<div
className={clsx(ThemeClassNames.wrapper.main, wrapperClassName, pageClassName)}
>
<ErrorBoundary fallback={ErrorPageContent}>{children}</ErrorBoundary>
</div>
</DarkModeMonitor>
</LayoutProviders>
);
};
export default Layout; |
Beta Was this translation helpful? Give feedback.
Answered by
pincman
Mar 7, 2022
Replies: 2 comments 1 reply
-
|
solved it const useThemeListener = () => {
const { isDarkTheme } = useColorMode();
const html = document.documentElement;
const observer = new MutationObserver((mutation) => {
const className = (mutation[0].target as any).className as string;
if (
(className.includes('tw-dark') && !isDarkTheme) ||
(!className.includes('tw-dark') && isDarkTheme)
) {
changeElement(isDarkTheme);
}
});
const changeElement = useCallback((isDark: boolean) => {
if (isDark) {
html.classList.add('tw-dark');
document.body.setAttribute('arco-theme', 'dark');
} else {
html.classList.remove('tw-dark');
document.body.removeAttribute('arco-theme');
}
}, []);
useEffect(() => {
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
changeElement(isDarkTheme);
return () => {
observer.disconnect();
html.classList.remove('tw-dark');
document.body.removeAttribute('arco-theme');
};
}, [isDarkTheme]);
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
pincman
-
|
This is a simple way to enable dark mode. https://tailwindcss.com/docs/dark-mode#customizing-the-class-name |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
solved it