From 1a018b70312363f38ef4cd3c9e224771886b270f Mon Sep 17 00:00:00 2001 From: Siriwat K Date: Mon, 21 Oct 2024 09:12:32 +0700 Subject: [PATCH] [system] Add `defaultMode` to `InitColorSchemeScript` (#44139) --- docs/data/material/customization/dark-mode/dark-mode.md | 8 ++++++++ .../src/InitColorSchemeScript/InitColorSchemeScript.tsx | 8 +++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/data/material/customization/dark-mode/dark-mode.md b/docs/data/material/customization/dark-mode/dark-mode.md index eed4715ff98bd4..a44b8226f49266 100644 --- a/docs/data/material/customization/dark-mode/dark-mode.md +++ b/docs/data/material/customization/dark-mode/dark-mode.md @@ -146,6 +146,14 @@ To set a different default mode, pass the `defaultMode` prop to the ThemeProvide The `defaultMode` value can be `'light'`, `'dark'`, or `'system'`. ::: +### InitColorSchemeScript component + +If you are using the `InitColorSchemeScript` component to [prevent SSR flicker](/material-ui/customization/css-theme-variables/configuration/#preventing-ssr-flickering), you have to set the `defaultMode` with the same value you passed to the `ThemeProvider` component: + +```js + +``` + ## Styling in dark mode Use the `theme.applyStyles` utility to apply styles for a specific mode. diff --git a/packages/mui-system/src/InitColorSchemeScript/InitColorSchemeScript.tsx b/packages/mui-system/src/InitColorSchemeScript/InitColorSchemeScript.tsx index 3c7d424de6ed5e..fa0a8b987ba7c3 100644 --- a/packages/mui-system/src/InitColorSchemeScript/InitColorSchemeScript.tsx +++ b/packages/mui-system/src/InitColorSchemeScript/InitColorSchemeScript.tsx @@ -8,6 +8,11 @@ export const DEFAULT_COLOR_SCHEME_STORAGE_KEY = 'color-scheme'; export const DEFAULT_ATTRIBUTE = 'data-color-scheme'; export interface InitColorSchemeScriptProps { + /** + * The default mode when the storage is empty (user's first visit) + * @default 'system' + */ + defaultMode?: 'system' | 'light' | 'dark'; /** * The default color scheme to be used on the light mode * @default 'light' @@ -49,6 +54,7 @@ export interface InitColorSchemeScriptProps { export default function InitColorSchemeScript(options?: InitColorSchemeScriptProps) { const { + defaultMode = 'system', defaultLightColorScheme = 'light', defaultDarkColorScheme = 'dark', modeStorageKey = DEFAULT_MODE_STORAGE_KEY, @@ -93,7 +99,7 @@ export default function InitColorSchemeScript(options?: InitColorSchemeScriptPro __html: `(function() { try { let colorScheme = ''; - const mode = localStorage.getItem('${modeStorageKey}') || 'system'; + const mode = localStorage.getItem('${modeStorageKey}') || '${defaultMode}'; const dark = localStorage.getItem('${colorSchemeStorageKey}-dark') || '${defaultDarkColorScheme}'; const light = localStorage.getItem('${colorSchemeStorageKey}-light') || '${defaultLightColorScheme}'; if (mode === 'system') {