Search code examples
reactjsmaterial-uitreeviewthemes

How to style MUI TreeItem component in my own Theme?


I want to assign colors to MUI TreeItem component. I found this thread but I want to do it using Theme style overrides in my own Theme. But I can't because TreeItem not in standard components list (but in '@mui/lab').

I tried to write section using this instruction but it generate an error: "TS2322: Type '{ MuiTreeItem: {}; }' is not assignable to type 'Components<Omit<Theme, "components">>'.   Object literal may only specify known properties, and 'MuiTreeItem' does not exist in type 'Components<Omit<Theme, "components">>'."

How can I include TreeItem colors into my Theme?


Solution

  • You need to add the following line:

    import type {} from "@mui/x-tree-view/themeAugmentation";
    

    Full working example:

    import * as React from "react";
    import { TreeView, TreeItem } from "@mui/x-tree-view";
    import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
    import ChevronRightIcon from "@mui/icons-material/ChevronRight";
    import { createTheme, ThemeProvider } from "@mui/material/styles";
    
    import type {} from "@mui/x-tree-view/themeAugmentation";
    
    const theme = createTheme({
      components: {
        MuiTreeItem: {
          styleOverrides: {
            root: {
              "& > .MuiTreeItem-content.Mui-selected": {
                color: "red",
              },
            },
          },
        },
      },
    });
    
    export default function FileSystemNavigator() {
      return (
        <ThemeProvider theme={theme}>
          <TreeView
            aria-label="file system navigator"
            defaultCollapseIcon={<ExpandMoreIcon />}
            defaultExpandIcon={<ChevronRightIcon />}
            sx={{ height: 240, flexGrow: 1, maxWidth: 400, overflowY: "auto" }}
          >
            <TreeItem nodeId="1" label="Applications">
              <TreeItem nodeId="2" label="Calendar" />
            </TreeItem>
            <TreeItem nodeId="5" label="Documents">
              <TreeItem nodeId="10" label="OSS" />
              <TreeItem nodeId="6" label="MUI">
                <TreeItem nodeId="8" label="index.js" />
              </TreeItem>
            </TreeItem>
          </TreeView>
        </ThemeProvider>
      );
    }
    

    CodeSandbox: https://codesandbox.io/p/sandbox/treeview-theme-customization-sn6w94?file=%2Fsrc%2FDemo.tsx%3A15%2C26