diff --git a/packages/eui/changelogs/upcoming/8040.md b/packages/eui/changelogs/upcoming/8040.md new file mode 100644 index 00000000000..0fc57f0a78b --- /dev/null +++ b/packages/eui/changelogs/upcoming/8040.md @@ -0,0 +1,3 @@ +**Bug fixes** + +- Fixed `EuiProvider`'s system color mode detection causing errors during server-side rendering diff --git a/packages/eui/src/components/provider/system_color_mode/system_color_mode_provider.server.test.tsx b/packages/eui/src/components/provider/system_color_mode/system_color_mode_provider.server.test.tsx new file mode 100644 index 00000000000..d05f44e68a7 --- /dev/null +++ b/packages/eui/src/components/provider/system_color_mode/system_color_mode_provider.server.test.tsx @@ -0,0 +1,29 @@ +/** + * @jest-environment node + */ +/* eslint-disable local/require-license-header */ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import React from 'react'; +import { renderToString } from 'react-dom/server'; + +import { EuiSystemColorModeProvider } from './system_color_mode_provider'; + +describe('EuiSystemColorModeProvider', () => { + it('handles server-side rendering without crashing', () => { + const children = jest.fn(() => <>Test); + + const renderOnServer = () => + renderToString(); + expect(renderOnServer).not.toThrow(); + + expect(renderOnServer()).toEqual('Test'); + expect(children).toHaveBeenCalledWith('LIGHT'); + }); +}); diff --git a/packages/eui/src/components/provider/system_color_mode/system_color_mode_provider.tsx b/packages/eui/src/components/provider/system_color_mode/system_color_mode_provider.tsx index 5396c967c37..9148a16e0cb 100644 --- a/packages/eui/src/components/provider/system_color_mode/system_color_mode_provider.tsx +++ b/packages/eui/src/components/provider/system_color_mode/system_color_mode_provider.tsx @@ -14,10 +14,13 @@ export const COLOR_MODE_MEDIA_QUERY = '(prefers-color-scheme: dark)'; export const EuiSystemColorModeProvider: FunctionComponent<{ children: (systemColorMode: EuiThemeColorModeStandard) => ReactElement; }> = ({ children }) => { - // Use optional chaining here for SSR or test environments + // Check typeof and use optional chaining for SSR or test environments const [systemColorMode, setSystemColorMode] = useState(() => - window?.matchMedia?.(COLOR_MODE_MEDIA_QUERY).matches ? 'DARK' : 'LIGHT' + typeof window !== 'undefined' && + window.matchMedia?.(COLOR_MODE_MEDIA_QUERY)?.matches + ? 'DARK' + : 'LIGHT' ); // Listen for system changes