reactjsmaterial-uithemeprovider

Override Box component in createTheme


I have an application that utilizes box's in place of where divs would typically be placed to stay within the MUI ecosystem. My question is, is it possible to have a global theme override for all box components much like how you can globally override the background color for all cards using theme provider.


Solution

  • You can override the Card styles globally using createTheme() because the Card has a name and a styleOverrides callback when it is styled using the styled() API. However, the Box does not, as you can see from the definition here.

    const theme = createTheme({
      components: {
        // this works
        MuiCard: {
          styleOverrides: {
            //
          }
        },
        // this does not work
        MuiBox: {
          styleOverrides: {
            //
          }
        }
      }
    });
    

    If you want to create a base component like the Box that can be styled globally by createTheme, you need to define the following properties in the options when calling styled()

    Below is the minimal example for demonstration:

    const theme = createTheme({
      components: {
        MuiDiv: {
          styleOverrides: {
            root: {
              backgroundColor: "green"
            }
          }
        }
      }
    });
    
    const Div = styled("div", {
      name: "MuiDiv",
      overridesResolver: (props, styles) => {
        return [styles.root];
      }
    })();
    
    <Div sx={{ width: 10, height: 10 }} />
    

    Live Demo

    Codesandbox Demo

    References