material-uimui-x-tree-view

How to get rid of horizontal scrollbar in Material-UI TreeView?


When trying out the Material-UI basic example for Tree View (@mui/lab/TreeView), I do not know how to remove the horizontal scrollbar when using the overflowY: "auto" (The same effect even if I use overflow: "auto") option in the sx prop of the TreeView component. The horizontal scrollbar appears no matter how much space is available to the right. I want to keep the overflowY option in case of vertical overflow.

enter image description here

For example please see the basic tree view example from the official Material-UI page in StackBlitz or CodeSandbox.

How to remove the horizontal scrollbar when it's not needed?


Solution

  • This happens because the CSS classes .MuiTreeItem-content and its child .MuiTreeItem-label are set to 100% width by default, therefore, the .MuiTreeItem-content's 8px padding on x axis (also default) get in the way, adding 16px too many. You can easily override this by setting .MuiTreeItem-content's class padding to 0.

    // ...
    
    import MuiTreeItem from "@mui/lab/TreeItem";
    import { styled } from "@mui/material/styles";
    
    const TreeItem = styled(MuiTreeItem)(({ theme }) => ({
      "& .MuiTreeItem-content": {
        padding: 0,
      },
    }));
    
    // ...