Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[material-ui] Return styles directly if the selector is & when using applyStyles #43633

Merged

Conversation

siriwatknp
Copy link
Member

@siriwatknp siriwatknp commented Sep 6, 2024

closes #43620

This is an edge case because ideally, there is no need to use theme.applyStyles for a single color scheme. It happens when using cssVariables with a single light or dark palette:

createTheme({
  cssVariables: true,
  palette: { mode: 'dark' }
});

With a single color scheme, the applyStyles('dark', styles) return { '&': styles }.
Emotion treats it as a different <style>, so the default styles of AppBar wins the one from the theme style overrides.

Before: https://codesandbox.io/p/sandbox/adoring-firefly-x6cktw?file=%2Fdemo.tsx%3A1%2C1-61%2C1

This PR fixes by returning the styles directly if the selector is & so that a new <style> is not created.

After: https://codesandbox.io/p/sandbox/material-ui-cra-ts-forked-fzf2m5

@siriwatknp siriwatknp added bug 🐛 Something doesn't work package: material-ui Specific to @mui/material customization: theme Centered around the theming features labels Sep 6, 2024
@mui-bot
Copy link

mui-bot commented Sep 6, 2024

Netlify deploy preview

https://deploy-preview-43633--material-ui.netlify.app/

Bundle size report

Details of bundle changes (Toolpad)
Details of bundle changes

Generated by 🚫 dangerJS against 0e77141

Copy link
Member

@DiegoAndai DiegoAndai left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How/why does Emotion treat & differently? I'm asking so I can understand the solution better 😊

@siriwatknp
Copy link
Member Author

How/why does Emotion treat & differently? I'm asking so I can understand the solution better 😊

Here is the proof using emotion styled directly:

styled.h1`
  font-size: 2rem;
  padding: 0;
  margin: 0 0 0.25rem 0;

  & {
    color: red;
  }
`;

The result:

image

I think this is done by the processor (stylus) inside Emotion, when it finds &, it creates a new array index of the styles. As a result the <style> is created more than one but the className is still the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug 🐛 Something doesn't work customization: theme Centered around the theming features package: material-ui Specific to @mui/material
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enabling cssVariables with dark mode on is changing the color of AppBar
3 participants