Last active
December 4, 2019 11:01
-
-
Save gauravsoti1/849e48fabc8a9879db4c2bb4ac8ac454 to your computer and use it in GitHub Desktop.
React Material UI modular dropdown component. This doesn't add overflow and padding style to the body when it opens.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
import styled from "styled-components"; | |
import { | |
MenuItem, | |
MenuList, | |
ClickAwayListener, | |
Paper, | |
Popper | |
} from "@material-ui/core"; | |
import ArrowDropDownOutlinedIcon from "@material-ui/icons/ArrowDropDownOutlined"; | |
import PropTypes from "prop-types"; | |
import { getRandomInt } from "constants/helper"; | |
// menuItems is an array of object like: {content: "", onClick: function} | |
export default function IconDropdown({ menuId, icon, menuItems }) { | |
// for maintaining open and close state | |
const [anchorEl, setAnchorEl] = useState(null); | |
const handleClick = event => { | |
setAnchorEl(anchorEl ? null : event.currentTarget); | |
}; | |
const handleClose = action => { | |
setAnchorEl(null); | |
}; | |
return ( | |
<DrodownContainer> | |
{// this is for how your icon would look} | |
<div onClick={handleClick}>{icon}</div> | |
<ArrowDropDownOutlinedIcon /> | |
{// ---------------} | |
<Popper | |
open={Boolean(anchorEl)} | |
anchorEl={anchorEl} | |
role={undefined} | |
transition | |
> | |
{// This is dropdown menu code} | |
<Paper> | |
<ClickAwayListener onClickAway={handleClose}> | |
<MenuList disablePortal id={menuId}> | |
{menuItems.map((item, i) => ( | |
<MenuItem | |
key={`${menuId}-item-${i}`} | |
onClick={() => handleClose(item.onClick)} | |
> | |
{item.content} | |
</MenuItem> | |
))} | |
</MenuList> | |
</ClickAwayListener> | |
</Paper> | |
{// ------------------ menu code ends here} | |
</Popper> | |
</DrodownContainer> | |
); | |
} | |
// styles to make sure the icon stays center aligned in the container | |
const DrodownContainer = styled.div` | |
position: relative; | |
display: flex; | |
align-items: center; | |
cursor: pointer; | |
`; | |
// by default we are generating a random id for the dropdown menu | |
IconDropdown.defaultProps = { | |
menuId: `simpleMenu${getRandomInt()}${getRandomInt()}` | |
}; | |
// For additional type checking | |
IconDropdown.propTypes = { | |
menuId: PropTypes.string, | |
icon: PropTypes.element.isRequired, | |
menuItems: PropTypes.array | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment