React Material UI Dropdown Menu With No Screen Shift

Gaurav Sobti
Nov 19, 2019
Body styles on opening modal

A modular component for material ui dropdown icon menu which doesn’t add the following styles to the body:

overflow: none;
padding: 15px

What are these styles doing?

You see your screen shifting to the right when you open a dropdown or modal bacause they hide the scrollbar on the right by saying no overflowing is allowed on the body.
This happens because by default dropdown menu uses Modal component behind scenes and it makes sense that body component shouldn’t scroll for a modal. But it doesn’t make sense for a dropdown.

The solution is to use MenuList instead of menu.

<Popper disablePortal open={Boolean(anchorEl)} anchorEl={anchorEl} role={undefined} transition > 
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList id={menuId}>
{menuItems.map((item, i) => (
<MenuItem
key={`${menuId}-item-${i}`}
onClick={() => handleClose(item.onClick)} >
{item.content}
</MenuItem> ))}
</MenuList>

</ClickAwayListener>
</Paper>
</Popper>

Below you can find the final gist. It is a modular component, in which you can easily pass your menu items, menuId, onClick function and forget about what’s happening behind the scenes.

The code uses styled-components for styling and prop-types for type checking component props.

--

--