formaat-design / reshaped

Community repository for storing examples, reporting issues and tracking roadmap
https://reshaped.so
97 stars 3 forks source link

How to achieve automatic color mode with server side rendering? #230

Closed hahahumble closed 3 months ago

hahahumble commented 3 months ago

How to implement automatic color mode with server side rendering when the mode is already specified in the root layout?

Color mode is already specified in the root layout:

<html lang="en" data-rs-theme="productTheme" data-rs-color-mode="light">
  <body
    className={inter.className}
    data-rs-theme="productTheme"
    data-rs-color-mode="light"
  >
    <ReshapedProvider>{children}</ReshapedProvider>
  </body>
</html>
blvdmitry commented 3 months ago

Hey, can you provide a bit more context about what you're trying to achieve? It's not super clear to me right now. Do you mean using the system color mode?

hahahumble commented 3 months ago

Yes, I mean how to achieve system color mode with SSR

blvdmitry commented 3 months ago

We have a documentation section about that here: https://reshaped.so/docs/getting-started/react/installation#system-dark-mode

Check the second list item there. General idea is that you can only access system settings of the user when you have access to the browser media queries. So to avoid FOUC , we recommend to handle that with an inline script tag that switches the color mode based on the media query. Since it's called synchronously before the HTML rendering, it would be able to set the correct mode attribute before the page is rendered.

<script
  dangerouslySetInnerHTML={{
    __html: `
      const matcher = window.matchMedia("(prefers-color-scheme: dark)");
      const systemColorMode = matcher.matches ? "dark" : "light";
      const storedColorMode = localStorage.getItem("__reshaped-mode");

      document.documentElement.setAttribute("data-rs-color-mode", storedColorMode || systemColorMode);
      matcher.addEventListener("change", () => {
        document.body.setAttribute("data-rs-color-mode", systemColorMode);
      });
  `,
  }}
/>
hahahumble commented 3 months ago

Okay, it's working properly now, thank you for your response.