Search code examples
cssreactjsmaterial-uimenuitemstyling

How to overried the selected classes in menuItem in material ui REACTjs?


hello i am having a problem I can't overried the classe that shows the right styling when a menuItem is selected : here is my code :

       <MenuItem component={Link} to="/Acceuil" 
        className={{root:classes.menuItem ,selected:classes.selected}} 
           selected={pathname === "/Acceuil"} >
              <ListItemIcon>
                  <Icon className={classes.icon} >
                      insert_drive_file
                   </Icon>
               </ListItemIcon>
            Gestion Commandes
        </MenuItem>

and this is the classes const :

      Const classes = theme => ({
       menuItem: {
         fontStyle:'bold',
         backgroundColor: 'white',
         width: '88%',
      '&:active':{
        borderLeft: '4px solid #51bcda',
        backgroundColor: "-webkit-box-shadow: 6px 4px 53px -7px 
        rgba(0,0,0,0.75), -moz-box-shadow: 6px 4px 53px -7px 
        rgba(0,0,0,0.75),   box-shadow: 6px 4px 53px -7px 
        rgba(0,0,0,0.75),",
        },
       selected:{
       backgroundColor:'red !important' 
       } 
       });

thanks for helping me ^^


Solution

  • To understand how to style this with the appropriate specificity, you need to look at the ListItem source code (MenuItem delegates most of its styling to ListItem).

    Here are the relevant portions of the ListItem styling for the selected state:

    export const styles = theme => ({
      root: {
        '&$selected, &$selected:hover, &$selected:focus': {
          backgroundColor: theme.palette.action.selected,
        },
      },
      /* Styles applied to the root element if `selected={true}`. */
      selected: {},
    });
    

    Below I've included an example of overriding the styling for the selected MenuItem along with a working CodeSandbox based on the Selected menus demo.

    const styles = theme => ({
      menuItemRoot: {
        "&$menuItemSelected, &$menuItemSelected:focus, &$menuItemSelected:hover": {
          backgroundColor: "red"
        }
      },
      menuItemSelected: {}
    });
    ...
                <MenuItem
                  classes={{
                    root: classes.menuItemRoot,
                    selected: classes.menuItemSelected
                  }}
    ...
    

    Edit Menu selected styling

    Here's a similar question/answer for a different Material-UI component: Styling BottomNavigation in React.js Material-UI