I'm currently struggling with anchorRef and I'm not entirely sure how it works because I'm new to react and have never used it before. So I receive this error from material UI the moment the onClickAway method is called which just sets the anchorRef to null although this warning only appears once after the component is rendered afterwards I don't get a warning again??? I tried useEffect so that when the component loads it sets the value to null but it did not work. Please any help will be greatly appreciated.
Failed prop type: Material-UI: the `anchorEl` prop provided to the component is invalid.
It should be an HTML element instance or a referenceObject
TableComponent
export default function TestTable() {
const [data, setData] = useState([
{
val1: 'test1',
val2: 'test2',
val3: 'test3',
val4: 'test4',
val5: 'test5',
},
{
val1: 'test1',
val2: 'test2',
val3: 'test3',
val4: 'test4',
val5: 'test5',
},
{
val1: 'test1',
val2: 'test2',
val3: 'test3',
val4: 'test4',
val5: 'test5',
}
]);
const [open, setOpen] = React.useState(false);
const [anchorRef, setAnchorRef] = useState(null);
const handleMenuToggle = (event) => {
setAnchorRef(event.currentTarget);
setOpen((prevOpen) => !prevOpen);
}
const handleMenuClose = (event) => {
if (anchorRef) {
setAnchorRef(null);
}
setOpen(false);
}
const method1 = () => {
handleMenuClose()
}
return (
<TableContainer component={Paper}>
<Table aria-label="bids table" size="small">
<TableHead>
<TableRow>
<TableCell align="left">Header1</TableCell>
<TableCell align="left">Header2</TableCell>
<TableCell align="left">Header3</TableCell>
<TableCell align="left">Header4</TableCell>
<TableCell align="left">Header5</TableCell>
<TableCell align="left"></TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map((row, index) => (
<TableRow key={index}>
<TableCell>{row.val1}</TableCell>
<TableCell>{row.val2}</TableCell>
<TableCell>{row.val3}</TableCell>
<TableCell>{row.val4}</TableCell>
<TableCell>{row.val5}</TableCell>
<TableCell className="pr-0" style={{width: '5%'}}>
<IconButton aria-label="options"
onClick={(e) => handleMenuToggle(e)}>
<MoreVertIcon />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<Popper open={open} anchorEl={anchorRef} role={undefined} transition disablePortal>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
style={{
transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom',
}}
>
<Paper>
<ClickAwayListener onClickAway={handleMenuClose}>
<MenuList id="split-button-menu">
<MenuItem onClick={method1}>
Menu Opt1
</MenuItem>
<MenuItem onClick={method1}>
Menu Opt1
</MenuItem>
<MenuItem onClick={method1}>
Menu Opt3
</MenuItem>
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
</TableContainer>
)
You should use Boolean(anchorEl) for Popper [enter image description here][1]