Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[EuiProvider] Fix SSR crashing during new system color mode detection #8040

Merged
merged 2 commits into from
Sep 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
@@ -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
Loading