Skip to content

Instantly share code, notes, and snippets.

@kgregory
Last active July 2, 2021 12:55
Show Gist options
  • Save kgregory/4008263f2ce415ac09cf10f977776fb2 to your computer and use it in GitHub Desktop.
Save kgregory/4008263f2ce415ac09cf10f977776fb2 to your computer and use it in GitHub Desktop.
Hook to establish the relationship between a button and its popup menu
/**
* A hook that helps establish the relationship between button and menu
* Intended for Material-UI IconButton and Menu components, but would work nicely elsewhere
*/
import type { MouseEventHandler } from "react";
import { useMemo, useState } from "react";
interface UseMenuResults {
ButtonProps: {
"aria-controls"?: string,
"aria-haspopup": "true",
onClick: MouseEventHandler<HTMLButtonElement>,
};
MenuProps: {
id?: string,
anchorEl: Element | null,
open: boolean,
onClose: MouseEventHandler<HTMLButtonElement>,
};
closeMenu: MouseEventHandler<HTMLButtonElement>;
}
const useMenu = (id?: string): UseMenuResults => {
const [anchorEl, setAnchorEl] = (useState < Element) | (null > null);
const onClose = () => {
setAnchorEl(null);
};
return useMemo(
() => ({
ButtonProps: {
"aria-controls": id,
"aria-haspopup": "true",
onClick: (event) => {
setAnchorEl(event.currentTarget);
},
},
MenuProps: {
id,
anchorEl,
open: Boolean(anchorEl),
onClose,
},
closeMenu: onClose,
}),
[anchorEl, id]
);
};
export default useMenu;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment