cssreactjsmaterial-ui

Control the width of menu component in Material-UI


I'm trying to implement a menu item with a login form in it. It works but the width is too small. Is there a way to change it? I couldn't find anything in the documentation about it.

import React from 'react';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';

export default function SimpleMenu() {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = event => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div>
      <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
        Open Menu
      </Button>
      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose}>Profile</MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>
    </div>
  );
}

Solution

  • I would go with makeStyles which helps you customize built in components from Material-UI. From the documentation (read further here: makeStyles):

    Link a style sheet with a function component using the hook pattern. This hook can be used in a function component. The documentation often calls this returned hook useStyles.

    The only solution what was working for me is the following:

    import { makeStyles } from '@material-ui/core';
    
    // ...
    
    const useStyles = makeStyles({
        customWidth: {
            '& div': {
                // this is just an example, you can use vw, etc.
                width: '350px',
            }
        }
    });
    
    // ...
    
    export default function SimpleMenu() {
       // ...
       const classes = useStyles();
    
       return (
          <Menu
             id="simple-menu"
             anchorEl={anchorEl}
             keepMounted
             open={Boolean(anchorEl)}
             onClose={handleClose}
             className={classes.customWidth}
           >
             <MenuItem onClick={handleClose}>Profile</MenuItem>
             <MenuItem onClick={handleClose}>My account</MenuItem>
             <MenuItem onClick={handleClose}>Logout</MenuItem>
           </Menu>
    

    Additionally just checked the documentation and I even did not find any related property for this purpose, so I would go with the suggested custom solution.