iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📘

Enabling Horizontal Scrolling for MUI Menu Content

に公開

On devices with small widths, the content of a menu may overflow the screen if it is too wide.
To address this, we can allow the content to be scrolled horizontally so the entire menu can be viewed.

Implementation

The key is to set the following two points in the properties of the Menu component:

  • slotProps / paper / style / overflowX: auto
  • MenuListProps / style / width: max-content
import './App.css';

import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';

const App = () => {
  return (
    <div className="content">
      <Menu
        open
        sx={{
          width: '10em',
        }}
        slotProps={{
          paper: {
            style: {
              overflowX: 'auto',
            },
          },
        }}
        MenuListProps={{
          style: {
            width: 'max-content',
          },
        }}
      >
        <MenuItem>VERY LONG MENU ITEM 1</MenuItem>
        <MenuItem>VERY LONG MENU ITEM 2</MenuItem>
        <MenuItem>VERY LONG MENU ITEM 3</MenuItem>
      </Menu>
    </div>
  );
};

export default App;

The internal implementation of the Menu component consists of a MenuList component placed inside a Popover component.
This is achieved by setting the overflow attribute on the Paper inside the Popover component and adjusting the width of the MenuList (a child of the Paper) to match the width of its MenuItem contents.

Environment

  • MUI v6

Discussion