Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
  );
}
like image 965
Alexander Avatar asked Oct 24 '19 16:10

Alexander


2 Answers

@norbitrial answer could have side effects. In my case i can't close the menu by clicking outside it !

Better use :

<Menu
  ...
  PaperProps={{  
    style: {  
      width: 350,  
    },  
 }} 
like image 150
abdelgrib Avatar answered Nov 04 '22 03:11

abdelgrib


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.

like image 33
norbitrial Avatar answered Nov 04 '22 03:11

norbitrial