volodymyr
volodymyr

Reputation: 11

Can't resolve '@mui/material/styles/useColorScheme' when adding theme switch to my MUI project

Problem Description

I’m working on a Next.js project using a Material-UI (MUI) template (version 6.3.0), and everything was functioning correctly. I started migrating the theme from the MUI template that I have bought, and the migration went fine. However, when I tried to implement a theme switch, I encountered the following error when I try to import useColorScheme() hook: Module not found: Can't resolve '@mui/material/styles/useColorScheme' compile error

There is my ThemeProvider.tsx

'use client';

import CssBaseline from '@mui/material/CssBaseline';
import { ThemeProvider as ThemeVarsProvider, createTheme } from '@mui/material/styles';
import { baseTheme } from './create-theme';
import { ReactNode } from 'react';

// TODO improve types for provider
interface Props {
  children: ReactNode;
  defaultMode?: 'light' | 'dark' | 'system';
  modeStorageKey?: string;
}

export const ThemeProvider = ({ children, ...other }: Props) => {
  const theme = createTheme(baseTheme, {}, {});

  return (
    <ThemeVarsProvider theme={theme} {...other}>
      <CssBaseline />
      {children}
    </ThemeVarsProvider>
  );
};

ThemeProvider from template. They use own createTheme because they provide ability to change colors schemes as it's demo but I removed that because I don't need it.

'use client';

import CssBaseline from '@mui/material/CssBaseline';
import { ThemeProvider as ThemeVarsProvider } from '@mui/material/styles';

import { useTranslate } from 'src/locales';

import { useSettingsContext } from 'src/components/settings';

import { createTheme } from './create-theme';
import { Rtl } from './with-settings/right-to-left';

// ----------------------------------------------------------------------

export function ThemeProvider({ themeOverrides, children, ...other }) {
  const { currentLang } = useTranslate();

  const settings = useSettingsContext();

  const theme = createTheme({
    settingsState: settings.state,
    localeComponents: currentLang?.systemValue,
    ...{},
  });

  return (
    <ThemeVarsProvider disableTransitionOnChange theme={theme} {...other}>
      <CssBaseline />
      <Rtl direction={settings.state.direction}>{children}</Rtl>
    </ThemeVarsProvider>
  );
}

There is my baseTheme:

export const baseTheme: any = {
  colorSchemes: {
    light: {
      palette: palette.light,
      shadows: shadows.light,
      customShadows: customShadows.light,
    },
    dark: {
      palette: palette.dark,
      shadows: shadows.dark,
      customShadows: customShadows.dark,
    },
  },
  mixins,
  components,
  typography,
  shape: { borderRadius: 8 },
  cssVariables: themeConfig.cssVariables,
  defaultColorScheme: themeConfig.defaultMode,
};

There is my dependencies

"@emotion/react": "^11.14.0",
    "@emotion/styled": "^11.14.0",
    "@hookform/resolvers": "^3.3.4",
    "@mui/icons-material": "^6.4.3",
    "@mui/lab": "6.0.0-beta.26",
    "@mui/material": "^6.4.3",
    "@mui/material-nextjs": "^6.4.3",
    "@mui/system": "^6.3.0",
    "@reduxjs/toolkit": "^2.2.1",
    "classnames": "^2.5.1",
    "dayjs": "^1.11.10",
    "eslint-plugin-simple-import-sort": "^12.0.0",
    "lint-staged": "^15.2.2",
    "next": "14.1.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-hook-form": "^7.51.0",
    "react-redux": "^9.1.0",
    "react-toastify": "^10.0.4",
    "redux-persist": "^6.0.0",
    "redux-thunk": "^3.1.0",
    "tailwind-merge": "^2.2.1",
    "ts-pattern": "^5.0.8",
    "zod": "^3.22.4"

And there is my layout.tsx where I use my provider

import { ReactNode } from 'react';
import { ToastContainer } from 'react-toastify';

// for MUI performance improvement
import type {} from '@mui/material/OverridableComponent';
import type {} from '@mui/material/themeCssVarsAugmentation';
import { AppRouterCacheProvider } from '@mui/material-nextjs/v14-appRouter';
import InitColorSchemeScript from '@mui/system/InitColorSchemeScript';
import type {} from '@mui/types/OverridableComponentAugmentation';
// import { Metadata } from 'next';
import { Inter } from 'next/font/google';

import { ReduxProvider } from '@/shared/store';
import { ThemeProvider } from '@/theme';
import { themeConfig } from '@/theme/theme-config';

import '../shared/styles/index.css';

const inter = Inter({ subsets: ['latin'] });

// export const metadata: Metadata = {
//   title: 'MP Frontend',
// };

interface RootLayoutProps {
  readonly children: ReactNode;
}

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <ReduxProvider>
      <html lang="en">
        <body suppressHydrationWarning className={inter.className}>
          <InitColorSchemeScript
            defaultMode={themeConfig.defaultMode}
            modeStorageKey={themeConfig.modeStorageKey}
            attribute={themeConfig.cssVariables.colorSchemeSelector}
          />

          <AppRouterCacheProvider options={{ key: 'css' }}>
            <ThemeProvider modeStorageKey={themeConfig.modeStorageKey}>
              <ToastContainer />
              {children}
            </ThemeProvider>
          </AppRouterCacheProvider>
        </body>
      </html>
    </ReduxProvider>
  );
}

and Header.tsx where I try to import it

'use client';

import React from 'react';
import { useColorScheme } from '@mui/material/styles';
import { Button, Switch } from '@mui/material';
import Image from 'next/image';
import Link from 'next/link';

import { useSelector } from '@/shared/store';
import { authSelectors } from '@/shared/store/entities/auth';

export const Header = () => {
  const isAuthenticated = useSelector(authSelectors.isAuthenticated);
  const { mode, setMode } = useColorScheme();

  return (
    <>
      <div className="fixed z-50 top-0 w-full h-[65px] px-4 py-3 flex justify-between items-center">
        <Link href="/">
          <Image src="/logo/logo-white.svg" alt="our-logo" width={82} height={48} />
        </Link>

        <Switch
          name="theme-switch"
          size="small"
          color="default"
          checked={mode === 'dark'}
          onChange={() => setMode(mode === 'dark' ? 'light' : 'dark')}
          sx={{ mr: -0.75 }}
        />

        <div className="flex items-center gap-3">
          {!isAuthenticated && (
            <Link href="/sign-in">
              <Button variant="outlined" color="warning">
                Login
              </Button>
            </Link>
          )}
        </div>
      </div>
    </>
  );
};

I've read everything about this hook and vars in MUI but a few days in a row can't fix it. I thought about creating own implementation for switching theme but anyway it's hard to do that as seemless as MUI do that.

Does somebody know what can be a problem I would appreciate it

What I Tried:

Upvotes: 0

Views: 36

Answers (0)

Related Questions