material-ui icon indicating copy to clipboard operation
material-ui copied to clipboard

[Menu] Not appearing in the correct place

Open matthewberkompas opened this issue 9 years ago • 20 comments

  • [x] I have searched the issues of this repository and believe that this is not a duplicate.

Thanks for the awesome library guys! I'm really pleased with it so far, other than the bug I've described below.

Expected Behavior

When I create an IconButton with a menu that activates on mouse click, the Menu should open on top of the IconButton because the Iconbutton has been set as the anchor element.

Current Behavior

Instead, the Menuopens in the far left corner of the page. See the screenshot below to see what I mean: stages leadsimple

Steps to Reproduce (for bugs)

I can't include the steps to reproduce since I'm copy-pasting the code which isn't working directly from the MUI docs about menus. Below is all my relevant code though:

handleClick = event => {
  this.setState({ open: true, anchorEl: event.currentTarget });
};

handleRequestClose = () => {
  this.setState({ open: false });
};

render() {
  return (
    <div>
      <IconButton
          aria-label="More"
          aria-owns={this.state.open ? 'simple-menu' : null}
          aria-haspopup="true"
          onClick={this.handleClick}
       >
          <Icon>more_vert</Icon>
       </IconButton>
       <Menu
          id="simple-menu"
          anchorEl={this.state.anchorEl}
          open={this.state.open}
          onRequestClose={this.handleRequestClose}
       >
           <MenuItem onClick={this.handleRequestClose}>Rename</MenuItem>
           <MenuItem onClick={this.handleRequestClose}>Merge and Delete</MenuItem>
       </Menu>
     </div>
  )
}

Note that this button is nested (a few components down) inside a Grid component so that may potentially be an issue. I did test the menu outside of the Grid component however and I still encountered this problem. Please help as soon as you can. Thanks!

My Environment

Tech Version
Material-UI v1.0.0-beta.8
React 15.6.1
browser Google Chrome

matthewberkompas avatar Sep 07 '17 23:09 matthewberkompas

Sorry, I have no clue about what's wrong here. We gonna need a live reproduction example to debug it. I'm closing for now.

oliviertassinari avatar Sep 08 '17 07:09 oliviertassinari

I solved the issue. It turned out to be user error so thanks for taking a look.

matthewberkompas avatar Sep 08 '17 16:09 matthewberkompas

Hey how did you resolve this? Having the same problem right now.

jordangotbaum avatar Nov 08 '17 23:11 jordangotbaum

Hi @jordangotbaum. I should have included my solution when I solved this issue back in September because I don't remember what my code looked like before. What I do remember is that it had something to do with using the Menu component inside a Material-UI <Paper /> component which I had applied custom styles using the withStyles function that comes with Material-UI. Here's what that component looks like when I initialize it: const ColoredPaper = withStyles(paperStyles)(Paper). And for the sake of example, below is the CSS referred to above as paperStyles:

const paperStyles = {
  root: {
    height: '54px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: `0 ${padding} 0 ${padding}`,
    margin: '0 auto 7px auto'
  }
}

When I use the component it looks like this:

<ColoredPaper>
  <menu component goes here>
</ColoredPaper>

Check if you're wrapping the Menu with a custom-styled component. If so, try using the regular component from Material-UI and see if that fixes the problem (in the example above, I would just use Paper).

Hope this helps!

matthewberkompas avatar Nov 08 '17 23:11 matthewberkompas

@jordangotbaum I was able to solve the issue by externalizing the whole Button and Menu (copy/paste of the material-ui demo example) into a separated component. Weird...

JohnCoding94 avatar May 24 '18 09:05 JohnCoding94

Come across the same question, same code, behave differently. So confused.

Bosn avatar Jun 17 '18 09:06 Bosn

@Bosn The solution I posted back in September is what I did to solve this problem. Reference that if you're still encountering this problem. Sorry I can't help more 😕

matthewberkompas avatar Jun 18 '18 17:06 matthewberkompas

Just had exact same problem, when menu was rendering in the wrong place. In my case, I had typo in one of the unrelated (separate component) function, like this:

if (window.innerWidth = 320) {
      console.log("smith");
}

Fixed it to window.innerWidth == 320 and the problem went away.

illyas3 avatar Oct 21 '18 06:10 illyas3

anchorEl | object , func |   | The DOM element used to set the position of the menu.

Check whether you have correctly used this option in menu .

Example : #<Menu #id="yourId" #anchorEl={anchorEl} #open={Boolean(anchorEl)} #onClose={this.handleCloseMenuItem} #> #<MenuItem #onClick={this.handleCloseMenuItem} #>Option1 #

#</Menu #>

Regards Edit I dont Know how to use markdown, Sorry for extra #

theBabayega avatar Feb 07 '19 06:02 theBabayega

Adding 3 attributes to <Menu /> fixed it for me

    getContentAnchorEl={null}
    anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
    transformOrigin={{ vertical: "top", horizontal: "center" }}

I found the solution from here https://stackoverflow.com/questions/48157863/how-to-make-a-dropdown-menu-open-below-the-appbar-using-material-ui

rahuls360 avatar Apr 22 '19 12:04 rahuls360

it is because you have not defined the anchor.

The Menu attribute - ** anchorEl **, is responsible for passing the location of the button that called it, not true to say this, but only to be easy to understand.

In this way, you should refer whenever there is a click. I suggest you use the reaction hooks, which makes the component clean.

React Stateful

  const [menuOpen, setMenuOpen] = useState(false)
  const [anchorEl, setAnchorEl] = useState(false)

  const handleClick = (event) => {
    const anchorEl = event.currentTarget
    this.setState({ ...this.state, menuOpen: !menuOpen , anchorEl })
  }

React Hooks

  const [menuOpen, setMenuOpen] = useState(false)
  const [anchorEl, setAnchorEl] = useState(false)

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget) // anchorEl = recebe a posicao do elemento que vai ser ancora
  }
return (
       <Menu
          anchorEl={anchorEl}
          open={menuOpen}
          onClose={handleClick }
        >
              
              {...}
        </Menu>
)

matheusicaro avatar May 05 '19 23:05 matheusicaro

@matheusicaro Does Material-UI raise a warning when the component is not used correctly?

oliviertassinari avatar May 06 '19 10:05 oliviertassinari

I had the same issue. After doing some digging, I found out that if I declare the useState of the anchorEl outside the component that I'm trying to anchor and try to pass the handleClick as props it would not work. I solved it by keeping the const [anchorEl, setAnchorEl] = useState(null) inside the element I'm trying to anchor the menu. Seems link menu and button need to be on the same component.

jcouso avatar May 25 '20 00:05 jcouso

I am also having this issue. For me it appears to be related to the styling. The demo on the Material UI site works, it works when I justify the anchored element to the top right (the menu opens in the correct position), but it doesn't work when I do this, and re-style my component: const ProfileAvatar = styled(Avatar)({ // Even with no styles inside of here, the issue appears. });

Literally, just changing the element I anchor to from a generic Avatar component to the above ProfileAvatar component will cause the menu to change from opening over the Avatar to opening in the top left. How strange.

EDIT: If I use the Hook API method, it works as intended.

I hope that this is useful to anyone having this issue.

tjbdev avatar May 29 '20 05:05 tjbdev

I have the same issue and log:

Popover.js:150 Material-UI: The `anchorEl` prop provided to the component is invalid.
The anchor element should be part of the document layout.
Make sure the element is present in the document or that it's not display none.

sytolk avatar Oct 22 '20 13:10 sytolk

@matheusicaro Thank you SO much, I spent hours trying to figure this out, and trying the other things I've seen suggested in multiple places to no avail. This was the only thing that worked. Having an issue now with the close event, but this is definitely progress

jkester1986 avatar Nov 05 '20 23:11 jkester1986

@matheuspiment This bug appearing because you anchorEl state is on incorrect place of component. The anchorEl should be the same scope of Menu

jeftarmascarenhas avatar Feb 11 '21 14:02 jeftarmascarenhas

When I am using custom button (created with function withStyles) have the same behavior - button is on bottom but menu is on top. But if I use standard button (without any others changes in my code) all work good :((

PS: Found solution Set ref to parent box element (div)

const anchorRef = useRef<HTMLDivElement>(null);
....
<div ref=anchorRef>
<StyledIconButton>...</StyledIconButton>
<MenuContainer  anchorEl={anchorRef.current}>...</MenuContainer>
</div>

mmorozov-noltic avatar Feb 16 '21 11:02 mmorozov-noltic

I had the same issue. After doing some digging, I found out that if I declare the useState of the anchorEl outside the component that I'm trying to anchor and try to pass the handleClick as props it would not work. I solved it by keeping the const [anchorEl, setAnchorEl] = useState(null) inside the element I'm trying to anchor the menu. Seems link menu and button need to be on the same component.

THANKYOU THANKYOU THANKYOU SO MUCH! It does work!!

ses-education avatar Jul 15 '21 06:07 ses-education

Even I am facing with the same issue menu is displaying in the top right can you please help me to fix this.

RoshiniAdapa avatar Oct 30 '21 09:10 RoshiniAdapa