okaryo.log

Displaying Material-UI Menu at Mouse Pointer Position on Click | okaryo.log

Displaying Material-UI Menu at Mouse Pointer Position on Click

    #MaterialUI

Introduction

Yesterday, I wrote an article titled “Displaying Material-UI Menu on Right Click”.

Since then, I have also implemented the functionality to display the Menu at the mouse pointer position when clicked, so I will summarize it here.

Approach

In the general usage of the Menu component, you pass the target element where the Menu should be displayed to the anchorEl property.

To display the Menu at the mouse pointer position when clicked, you can use the anchorReference and anchorPosition properties.

<Menu
  anchorReference="anchorPosition"
  anchorPosition={anchorPostion}
>

The value passed to anchorPosition has the following type:

type AnchorPosition = { top: number; left: number } | null;

It requires the relative position of the mouse pointer (top and left) within the application.

These values can be obtained from the clientY and clientX properties of the click event. Here is a sample code:

type AnchorPosition = { top: number; left: number } | null;

const [menuAnchorPosition, setMenuAnchorPosition] = useState<AnchorPosition | null>(null);
const onClick = (event: React.MouseEvent<HTMLElement>) => {
  setMenuAnchorPosition({ top: event.clientY, left: event.clientX });
};
const onCloseMenu = () => {
  setMenuAnchorPosition(null)
}

return (
  <div>
    <Button onClick={onClick}>
      Click Target
    </Button>
    <Menu
      open={Boolean(anchorPosition)}
      onClose={onCloseMenu}
      anchorReference="anchorPosition"
      anchorPosition={anchorPostion}
    >
      <MenuItem onClick={onCloseMenu}>Item</MenuItem>
    </Menu>
  </div>
)

Now, the Menu will be displayed at the clicked position.

Conclusion

Displaying the Menu at the click position is particularly useful when the click target is large.

When displaying the Menu on an icon click, the click position and the Menu’s display position are usually close enough, so it’s not a concern.

However, in cases where the click target has a large size, the distance between the click position and the Menu can become significant. In such cases, the approach described in this article can be effective. However, it’s important to consider potential overlap between the click target and the Menu on a case-by-case basis.


Related Posts
Related Posts
Promotion

This site uses Google Analytics.