Material-ui don't change the style when the MenuItem has selected

Viewed 22

Currently, I styled background-color: red; if the MenuItem that has selected={true}

and if I hover the option, MenuItem background-color will change to green.

But when I hover over the MenuItem that has selected={true}, the background-color will be light-blue which is mui default.

I'd like to keep background-color: red; for MenuItem that has selected={true} even if this component get hovered over.

index.js

import * as React from "react";
import Paper from "@mui/material/Paper";
import MenuList from "@mui/material/MenuList";
import Stack from "@mui/material/Stack";
import { MenuItem } from "./styles";

export default function MenuListComposition() {
  return (
    <Stack direction="row" spacing={2}>
      <Paper>
        <MenuList>
          <MenuItem selected={true}>Profile</MenuItem>
          <MenuItem>My account</MenuItem>
          <MenuItem>Logout</MenuItem>
        </MenuList>
      </Paper>
    </Stack>
  );
}

styles.js

import styled from "styled-components";
import { default as MuiMenuItem } from "@mui/material/MenuItem";

export const MenuItem = styled(MuiMenuItem)`
  color: blue;
  padding: 20px;

  &.Mui-selected {
    background-color: red;
  }

  &:hover {
    background-color: green;
  }
`;

1 Answers

You are almost there, just need to add the &.Mui-selected:hover to overwrite the default background color.

export const MenuItem = styled(MuiMenuItem)`
  color: blue;
  padding: 20px;

  &.Mui-selected {
    background-color: red;
  }

  // Add this
  &.Mui-selected:hover{ 
    background-color: red;
  }

  &:hover {
    background-color: green;
  }
`;

Here is the working codesandbox

Related