diff --git a/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-mantine-color-scheme.test.tsx b/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-mantine-color-scheme.test.tsx index 6c9f9b5e51a..e4e14c2aa13 100644 --- a/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-mantine-color-scheme.test.tsx +++ b/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-mantine-color-scheme.test.tsx @@ -11,4 +11,15 @@ describe('@mantine/core/MantineProvider/use-mantine-color-scheme', () => { const { result } = renderHook(() => useMantineColorScheme(), { wrapper: Wrapper }); expect(result.current.colorScheme).toBe('dark'); }); + + describe('with default values', () => { + function DefaultWrapper({ children }: { children: React.ReactNode }) { + return {children}; + } + + it('returns the correct color schema based on prefers-color-scheme', () => { + const { result } = renderHook(() => useMantineColorScheme(), { wrapper: DefaultWrapper }); + expect(result.current.colorScheme).toBe('light'); + }); + }); }); diff --git a/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-provider-color-scheme.ts b/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-provider-color-scheme.ts index 2dfd065ad16..54fc864baef 100644 --- a/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-provider-color-scheme.ts +++ b/packages/@mantine/core/src/core/MantineProvider/use-mantine-color-scheme/use-provider-color-scheme.ts @@ -7,12 +7,13 @@ function setColorSchemeAttribute( colorScheme: MantineColorScheme, getRootElement: () => HTMLElement | undefined ) { + const hasDarkColorScheme = + typeof window !== 'undefined' && + 'matchMedia' in window && + window.matchMedia('(prefers-color-scheme: dark)').matches; + const computedColorScheme = - colorScheme !== 'auto' - ? colorScheme - : window.matchMedia('(prefers-color-scheme: dark)').matches - ? 'dark' - : 'light'; + colorScheme !== 'auto' ? colorScheme : hasDarkColorScheme ? 'dark' : 'light'; getRootElement()?.setAttribute('data-mantine-color-scheme', computedColorScheme); } @@ -71,7 +72,10 @@ export function useProviderColorScheme({ setColorSchemeAttribute(value, getRootElement); } - media.current = window.matchMedia('(prefers-color-scheme: dark)'); + if (typeof window !== 'undefined' && 'matchMedia' in window) { + media.current = window.matchMedia('(prefers-color-scheme: dark)'); + } + const listener: MediaQueryCallback = (event) => { if (value === 'auto') { setColorSchemeAttribute(event.matches ? 'dark' : 'light', getRootElement);