Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 839
Ashutosh Avatar asked Jul 13 '20 14:07

Ashutosh


2 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.

like image 124
Ashutosh Avatar answered Oct 19 '22 08:10

Ashutosh


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>
}
like image 1
Peter Hayman Avatar answered Oct 19 '22 06:10

Peter Hayman