Skip to content

Commit

Permalink
[EuiProvider] Fix SSR crashing during new system color mode detection (
Browse files Browse the repository at this point in the history
  • Loading branch information
cee-chen committed Sep 24, 2024
1 parent 80dacb3 commit 0ae4d7f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
3 changes: 3 additions & 0 deletions packages/eui/changelogs/upcoming/8040.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
**Bug fixes**

- Fixed `EuiProvider`'s system color mode detection causing errors during server-side rendering
Original file line number Diff line number Diff line change
@@ -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(<EuiSystemColorModeProvider children={children} />);
expect(renderOnServer).not.toThrow();

expect(renderOnServer()).toEqual('Test');
expect(children).toHaveBeenCalledWith('LIGHT');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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<EuiThemeColorModeStandard>(() =>
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
Expand Down

0 comments on commit 0ae4d7f

Please sign in to comment.