How to use multiple CSS classes with MUI 5 SX prop?

Viewed 4652

Does anyone know how to use multiple CSS classes with MUI 5 SX prop? I created a base class that I want to use with my Box components but use a second class specifically for the text inside of the Box. Applying base class, such as sx={styles.baseBoxStyle} works but sx={styles.baseBoxStyle styles.customBoxFontStyle} returns an error. Full code snippet and sandbox provided below. Any assistance is greatly appreciated!

Sandbox: https://codesandbox.io/s/mui-5-styling-uqt9m?file=/pages/index.js

import * as React from "react";
import Box from "@mui/material/Box";

const styles = {
  baseBoxStyle: {
    backgroundColor: "red",
    borderRadius: "20px 20px 20px 20px",
    border: "1px solid black",
    maxWidth: "150px",
    margin: "20px",
    padding: "10px"
  },
  customBoxFontStyle: {
    color: "yellow",
    fontWeight: "bold"
  }
};

export default function Index() {
  return <Box sx={styles.baseBoxStyle styles.customBoxFontStyle}>This is a test</Box>;
}
5 Answers

For a simple solution, can deconstruct the style objects and compile into one object.

<Box sx={{...styles.baseBoxStyle,...styles.customBoxFontStyle}}>This is a test</Box>

You can try to use classnames as its commonly used library, or you can just make string from these styles that you pass into sx sx={styles.baseBoxStyle+' '+styles.customBoxFontStyle}

I think you cant use sx with classes. I have not seen any example in documentation.

If you want combine 2 calsses, and you get one of them as props you should work like this

const componnent = (styles) => {
 return ( 
  <ListItem
    sx={[
      {
        width: 'auto',
        textDecoration: 'underline',
      },
      ...(Array.isArray(styles) ? styles : [styles]),
    ]}
  /> 
 )
}

You cannot spread sx directly because SxProps (typeof sx) can be an array

Related