I have created MUI Nav bar which has a couple of items on the right. Upon clicking on the user icon a dropdown menu should be displayed. The menu pops up but I get this error –
Warning: Failed prop type: MUI: The `anchorEl` prop provided to the component is invalid. It should be an Element instance but it's `undefined` instead. at Popover (https://inq73y.csb.app/node_modules/@mui/material/Popover/Popover.js:97:43) at eval (https://inq73y.csb.app/node_modules/@emotion/react/dist/emotion-element-b63ca7c6.cjs.dev.js:43:23) at Menu (https://inq73y.csb.app/node_modules/@mui/material/Menu/Menu.js:72:43) at header at eval (https://inq73y.csb.app/node_modules/@emotion/react/dist/emotion-element-b63ca7c6.cjs.dev.js:43:23) at Paper (https://inq73y.csb.app/node_modules/@mui/material/Paper/Paper.js:62:43) at eval (https://inq73y.csb.app/node_modules/@emotion/react/dist/emotion-element-b63ca7c6.cjs.dev.js:43:23) at AppBar (https://inq73y.csb.app/node_modules/@mui/material/AppBar/AppBar.js:107:43) at div at eval (https://inq73y.csb.app/node_modules/@emotion/react/dist/emotion-element-b63ca7c6.cjs.dev.js:43:23) at Box (https://inq73y.csb.app/node_modules/@mui/system/esm/createBox.js:27:40) at ElevationScroll (https://inq73y.csb.app/src/App.js:32:28) at App (https://inq73y.csb.app/src/App.js:43:33)
I have also tried using anchorEl in state and adding it to the menu as described in the MUI docs but in this approach, the menu pops up on the top left instead of right and there is a warning which seems like the same issue to me.
MUI: 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. in Transition (created by Grow) in Grow (created by FocusTrap) in FocusTrap (created by ModalUnstyled) in ModalUnstyled (created by Modal) in Modal (created by MuiPopoverRoot) in MuiPopoverRoot (created by Popover) in Popover (created by MuiMenuRoot) in MuiMenuRoot (created by Menu) in Menu (created by App) in App
I have searched a couple of links using refs and getting the nested components out of the parent but I was not able to get those.
This is the link to codesandbox – CodeSandbox
Any help is appreciated. Thanks
2
Answers
ok, so if we provide the ref as below it works, the waring itself describes it
But I'm not able to understand what difference it makes upon passing it as a function rather than
The
anchorEl
property is expecting an element that is always available. The code you have removes this element on close – this is the cause of the error. The expected way to do it is to provide aref
(which is done via theuseRef
hook) to the element you want to be the anchor and control the visibility of the menu by itsopen
property.I made some changes to your code and got the error to go away.