I have a table
list where each row has a menu
button, for which I need a ref
. I am using react mui in my project and it's menu. I have tried creating the refs like this:
const {rows} = props;
const refs = Array.from({length: rows.length}, a => React.useRef<HTMLButtonElement>(null));
And then tried to use the inside the map
function like this on each button
:
<Button
ref={refs[index]}
aria-controls="menu-list-grow"
aria-haspopup="true"
onClick={() => handleToggle(row.id)}
>Velg
</Button>
<Popper open={!!checkIfOpen(row.id)} anchorEl={refs[index].current} keepMounted transition disablePortal>
{({TransitionProps, placement}) => (
<Grow
{...TransitionProps}
style={{transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom'}}>
<Paper id="menu-list-grow">
<ClickAwayListener onClickAway={(e) => handleClose(e, refs[index].current)}>
<MenuList>
<MenuItem
onClick={(e) => handleClose(e, refs[index].current)}>Profile</MenuItem>
<MenuItem onClick={(e) => handleClose(e, refs[index].current)}>My account</MenuItem>
<MenuItem onClick={(e) => handleClose(e, refs[index].current)}>Logout</MenuItem>
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
But, then I get an error:
React Hook "React.useRef" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
How can I do this dynamically, so that I can use refs inside the map function. I have tried with the suggestion in the answers, but I couldn't get it to work. Here is the codesandbox of the example.