mui / pigment-css

Pigment CSS is a zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build time.
MIT License
389 stars 18 forks source link

[nextjs] `useTheme` replacement does not work #124

Closed siriwatknp closed 2 weeks ago

siriwatknp commented 3 weeks ago

Search keywords

useTheme nextjs

Latest version

Steps to reproduce

use useTheme from ../zero-styled to let Pigment CSS process.

Current behavior

Got error at build time:

image

As I dug deeper, I found that Next.js wraps the component before passing to Pigment like the snippet below:

const Component = /*#__PURE__*/_s(React.forwardRef(_c = _s(function Component(inProps, ref) {
  _s();
  const props = useThemeProps({
    props: inProps,
    name: "MuiIconButton"
  });
  return …
}, "526RDEpO1CGEADq5vnCvoNyCejQ=", false, function () {
  return [useThemeProps, useTheme, useUtilityClasses];
})), "526RDEpO1CGEADq5vnCvoNyCejQ=", false, function () {
  return [useThemeProps, useTheme, useUtilityClasses];
});

Since Pigment replaces useTheme with a variable, I think that's why useTheme is no longer available when Next.js before building the page at the end.

Expected behavior

The page should be rendered without any error.

Context

I am trying to use useTheme processor in https://github.com/mui/material-ui/pull/42476

Your environment

npx @mui/envinfo ``` Don't forget to mention which browser you used. Output from `npx @mui/envinfo` goes here. ```
siriwatknp commented 3 weeks ago

@brijeshb42 I believe that useTheme should be changed to createUseTheme (we can add internal_ prefix to it) and update the runtime createUseTheme:

// runtime createUseTheme
import theme from '@pigment-css/react/theme';

export default function createUseTheme() {
  return function useTheme() {
    return theme;
  }
}

So that Pigment does not replace the useTheme in the consumer codebase:

import { createUseTheme } from '../zero-styled';

const useTheme = createUseTheme();

function Component() {
  const theme = useTheme();
}
brijeshb42 commented 2 weeks ago

@siriwatknp Is there a PR/branch to test the useTheme changes in material-ui ? I wanted to test few approaches.

siriwatknp commented 2 weeks ago

Is there a PR/branch to test the useTheme changes in material-ui ? I wanted to test few approaches

You can test it at https://github.com/mui/material-ui/pull/42476 using the apps/pigment-nextjs-app.

FYI, I tried with this but does not work too:

// mui-material/src/Tooltip
import { useTheme } from '../zero-styled';

const useLocalTheme = () => useTheme();

…

function Tooltip() {
  const theme = useLocalTheme();
}

Nextjs wraps the useLocalTheme with useTheme dependencies too and since useTheme is replaced by Pigment, Nextjs throw the same error.