Different modes within nested providers in @mui/joy

97 Views Asked by At

Joy-UI is certainly a joy to work with!

However, I'm having problems when trying to use different modes (light/dark) within nested providers. When calling setMode within a nested provider I was expecting it to only toggle the mode in the nearest provider, but that does not seem to be the case. It changes both the parent's and nested provider's mode.

I've tried using different keys for the provider storages as well as using disableNestedContext without luck.

Here is small example:

<CssVarsProvider>
     {setMode("light") /* Top provider is now light */}
  <CssVarsProvider>
     {setMode("dark") /* Both providers are now dark, but the parent should be light */}
  </CssVarsProvider>
</CssVarsProvider>

Also a live demo here:

Live demo

Thanks in advance!

1

There are 1 best solutions below

0
judehall On BEST ANSWER

Boom! After digging through the repo I found this commit. Which led me to a solution which consists of three different parts:

  1. Give each provider's theme a unique cssVarPrefix
  2. Nested providers should have disableNestedContext set
  3. Nested providers should have a unique attribute set

Pseudo example

<CssVarsProvider theme={extendTheme({ cssVarPrefix: "parent"})}>
  { setMode("light"); /* parent is now light */}

  <CssVarsProvider
    theme={extendTheme({ cssVarPrefix: "nested" })}
    disableNestedContext
    attribute="data-nested-color-scheme"
  >
    { setMode("dark"); /* only nested is now dark */}
  </CssVarsProvider>
</CssVarsProvider>;

Live demo here