I've written a simple hook to display a popper menu when a button is clicked, I'm having an issue passing the buttonRef, It seems to be passing it to the component however the element is not positioned correctly as if it isn't passed at all.
I've included an example on codeSanbox: https://codesandbox.io/s/9o03qx3n3o
I've confirmed this works when not inside the hook, React dev tools shows it's passing the same element in both instances. I've tried using forwardRef, same issue, I've tried using the standard state to store the ref to no avail;
--- Hook ---
const usePopperMenu = btnRef => {
const [open, setOpen] = useState(false);
const handleClose = event => {
if (btnRef.current.contains(event.target)) {
return;
}
setOpen(false);
};
const elems = ({ children }) => (
<Popper
open={open}
anchorEl={btnRef.current}
placement="bottom"
transition
disablePortal
>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
id="menu-list-grow"
style={{
transformOrigin:
placement === "bottom" ? "center top" : "center bottom"
}}
>
<Paper>
<ClickAwayListener onClickAway={e => handleClose(e)}>
<MenuList>{children}</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
);
return [elems, setOpen, open];
};
--- App/Component ---
function App() {
const btnRef = useRef(null);
const [Menu, setOpen, open] = usePopperMenu(btnRef);
return (
<div className="App">
<div>
<Button
buttonRef={btnRef}
onClick={() => setOpen(!open)}
variant="outlined"
color="secondary"
>
Click Me!
</Button>
<Menu>
<MenuItem>
<Typography color="textPrimary">Menu Item 1</Typography>
</MenuItem>
<MenuItem>
<Typography color="textPrimary">Menu Item 2</Typography>
</MenuItem>
</Menu>
</div>
</div>
);
}
It works good for me - problem is with your css styles. Button container is full size and display:grid thats why dropdown is misplaced
Try:
.App {
display: flex;
justify-content: center;
}
https://codesandbox.io/s/oprzyv665?fontsize=14
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With