Happy1234
Happy1234

Reputation: 729

why backgroundColor applies the place where I didn't mean to | Menu component from MUI | styled-components

I set background color pink to the Menu component from mui and this is what I'm seeing when I click dashboard button.

enter image description here

I expected this to add background color to the menu but turned out that half of the page got colored pink.

How can I apply background color to the menu?

import * as React from "react";
import Button from "@mui/material/Button";
import MenuItem from "@mui/material/MenuItem";
import { MenuRaw } from "./styles";

export default function BasicMenu() {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div>
      <Button
        id="basic-button"
        aria-controls={open ? "basic-menu" : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleClick}
      >
        Dashboard
      </Button>
      <MenuRaw
        id="basic-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        MenuListProps={{
          "aria-labelledby": "basic-button"
        }}
      >
        <MenuItem onClick={handleClose}>Profile</MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </MenuRaw>
    </div>
  );
}

import styled from "styled-components";
import Menu from "@mui/material/Menu";

export const MenuRaw = styled(Menu)`
  width: 412px;
  background-color: pink;
`;

Upvotes: 0

Views: 56

Answers (1)

Dmitriif
Dmitriif

Reputation: 2433

You need to specify the class of the menu element that you want to change. In this case you want to overwrite the .MuiPaper-root class of Paper component:

export const MenuRaw = styled(Menu)`
  & .MuiPaper-root {
    background-color: pink;
    width: 412px;
  }
`;

Upvotes: 1

Related Questions