Observed this Error: Material-UI: The `anchorEl` prop provided to the component is invalid

Viewed 21354

Observed the error when tried to open a popper in grid table. Error Details

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.

below is sample code I am using in grid table:

<>
    <MoreVertIcon
    ref={anchorRef}
    aria-controls={open ? 'menu-list-grow' : undefined}
    aria-haspopup="true"
 // key={uuidv4()}
    onClick={handleToggle}
    style={{ color: theme.palette.primary.main }}
    />
    <Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
        hello world
    </Popper>
</>

found a reference but not sure where I am breaking this norm. Any help is appreciated.

3 Answers

Finally got the reason, child component was re-rendering because I added dynamic key on map iteration which were causing props to change, as I used iteration index as key issue resolved.

Another way that this error can occur is when using a react ref. There can be a 'race condition' where the element is created before it is rendered, it can be solved by delaying setting the anchor by a frame:

const MyComponent = () => {
    const anchorRef = React.useRef()
    const [anchorEl, setAnchorEl] = React.useState()
    React.useEffect(() => { 
        setTimeout(() => setAnchorEl(anchorRef?.current), 1) 
    },  [anchorRef])

    return <div ref={anchorRef}>
        {anchorEl && <Popper anchorEl={anchorEl}>hello world</Popper>}
    </div>
}

In my case the issue was due to the fact my button IconButton was not receiving the actual ref={anchorRef}. Yep, that silly issue...

Also, in my case, I could do well with a name key other than an index like:

{optionsArray.map(option => (
     <MenuItem key={option} onClick={handleClose}>
          {option}
     </MenuItem>
))}
Related