Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

feat(useSetDocumentColorScheme): set document color scheme css hook #2880

Merged
merged 8 commits into from Oct 6, 2022
10 changes: 3 additions & 7 deletions src/components/DarkModeToggle/index.tsx
@@ -1,18 +1,14 @@
import React, { useEffect } from 'react';
import React from 'react';
import { useTheme } from '@skagami/gatsby-plugin-dark-mode';
import ModeNightIcon from '@mui/icons-material/ModeNight';
import BrightnessMediumIcon from '@mui/icons-material/BrightnessMedium';
import { useSetDocumentColorScheme } from '../../hooks/useSetDocumentColorScheme';
import styles from './index.module.scss';

const DarkModeToggle = () => {
const [theme, toggleTheme] = useTheme();

useEffect(() => {
// This is responsible for setting the color-scheme of the scroll-bars
if (typeof document === 'object' && document.documentElement) {
document.documentElement.style['color-scheme'] = theme;
}
}, [theme]);
useSetDocumentColorScheme(theme);

const handleThemeOnClick = (isKeyPress = false): void => {
if (isKeyPress) {
Expand Down
10 changes: 10 additions & 0 deletions src/hooks/useSetDocumentColorScheme.ts
@@ -0,0 +1,10 @@
import { useEffect } from 'react';

export function useSetDocumentColorScheme(theme: string | null): void {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I think this should be something like:

export function useSetDocumentColorScheme(): void {
  const [currentTheme, setCurrentTheme] = useState();

  useEffect(() => {
    // This is responsible for setting the color-scheme of the scroll-bars
    if (typeof document === 'object' && document.documentElement) {
      document.documentElement.style['color-scheme'] = theme;
    }
  }, [currentTheme]);

  return (theme: string | null) => setCurrentTheme(theme);
}

useEffect(() => {
// This is responsible for setting the color-scheme of the scroll-bars
if (typeof document === 'object' && document.documentElement) {
document.documentElement.style['color-scheme'] = theme;
}
}, [theme]);
}