Style Mui child component within parent component using CSS modules

Viewed 1406

I am following these docs in order to style a material ui component (Paper) within a component (Menu) I am using.

I am using CSS modules to style my components (with Webpack as a bundler) :

// menu.js

import React from 'react';
import { StyledEngineProvider } from '@mui/material/styles';
...
import styles from './styles.module.css';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';


const MyMenu = (props) => {
  ...
  return (
    <StyledEngineProvider injectFirst>
      <div id="my-menu">
        <Button id="button-react-component" onClick={handleClick}>
          My Menu
        </Button>
        <Menu
          id="menu-react-component"
          ...
          className={styles.menu}
        >
          <MenuItem ...>
            <span> Example 1 <span>
          </MenuItem>
        </Menu>
      </div>
  );
}

// styles.module.css


.menu {
  color: white;
}

.menu .MuiPaper-root {
  background-color: red
}

// Also tried : 
.menu .root {
  background-color: red
}

My goal is to have the MuiPaper component have a given background-color. MuiPaper is a component that comes from the Menu component, but I am not using MuiPaper directly as I am only declaring the parent (<Menu>).

Ideally I want to use .css files for styling. I use webpack to bundle my css files into modules.

Here's what I see in my browser : enter image description here

enter image description here

Notice how the background-color "red" is not applied on that last screenshot.

Thanks :)

1 Answers

CSS modules can't override a style from another CSS module (or elsewhere). There's a few ways to get around this:

  1. Add another class specifically for the .menu paper, e.g. .menuPaper, and add it via PaperProps on the Menu component:
.menuPaper {
  background-color: blue;
}
<Menu
  id="menu-react-component"
  ...
  className={styles.menu}
  PaperProps={{ className: styles.menuPaper }}
>

  1. Add the :global selector to your css selector:
.menu :global .MuiPaper-root {   
    background-color: red; 
}

CSS modules work by "modulifying" CSS classnames by adding a unique ID to the end of them. The :global selector can be used to disable this and preserve the classname instead.

The difference between these two methods is that if you had multiple Menu components in your MyMenu component, using the :global method would give all the Menu instances inside of MyMenu the same background. With the PaperProps method only specific Menus with PaperProps={{ className: styles.menuPaper }} would get the styles applied.

css-loaderdocs: https://github.com/webpack-contrib/css-loader#scope

MUI Menu docs: https://mui.com/api/menu/#props (also see Popover component)

Related