swordev / suid

A port of Material-UI (MUI) built with SolidJS.
https://suid.io
MIT License
682 stars 49 forks source link

Automatic dark theme is not working #289

Closed Azq2 closed 2 months ago

Azq2 commented 7 months ago
function App() {
    let drawerWidth = 240;

    let prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
    let theme = createMemo(() => {
        console.log('prefersDarkMode=', prefersDarkMode());
        return createTheme({
            palette: {
                mode: prefersDarkMode() ? 'dark' : 'light',
                primary: {
                    main: prefersDarkMode() ? '#b39ddb' : '#673ab7',
                },
                secondary: {
                    main: prefersDarkMode() ? '#673ab7' : '#651fff',
                },
            },
            typography: {
                fontFamily: [
                    '-apple-system',
                    'BlinkMacSystemFont',
                    '"Segoe UI"',
                    'Roboto',
                    '"Helvetica Neue"',
                    'Arial',
                    'sans-serif',
                    '"Apple Color Emoji"',
                    '"Segoe UI Emoji"',
                    '"Segoe UI Symbol"',
                ].join(','),
            }
        });
    });

    return (
        <SerialProvider>
            <ThemeProvider theme={theme()}>
                ....
            </ThemeProvider>
        </SerialProvider>
    );
}

I see console.log('prefersDarkMode=', prefersDarkMode()); on the console, but the theme is not changed.

s0ftik3 commented 5 months ago

Encountered the same issue just recently. Basically you don't need to use createMemo for theme variable. Below is the code that worked for me.

const palette = createMemo(() => {
    return createPalette(mode() === 'light' ? light : dark)
})
const theme = createTheme({ palette })

<ThemeProvider theme={theme}></...>

yet you can read this to see more details about it.

juanrgm commented 2 months ago

The explanation on StackOverflow is perfect.

You can use createPalette or right now with this patch (https://github.com/swordev/suid/commit/6406d78845ef694b044c36a7739edf823c6f286a) you can use the next code without problems:

import {
  Button,
  createTheme,
  CssBaseline,
  ThemeProvider,
} from "@suid/material";
import { createMemo, createSignal } from "solid-js";

export function App() {
  const [darkMode, setDarkMode] = createSignal(false);
  const theme = createMemo(() =>
    createTheme({
      palette: {
        mode: darkMode() ? "dark" : "light",
      },
    })
  );

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline enableColorScheme />
      <Button variant="outlined" onClick={() => setDarkMode(!darkMode())}>
        setDarkModel({(!darkMode()).toString()})
      </Button>
    </ThemeProvider>
  );
}