'MUI 5 className and SX prop show [object] instead of CSS class
I'm struggling to grasp styling changes in MUI 5. I have a bunch of styling which was working fine in Material UI 4 but when trying to apply the same styling in MUI 5 my web inspector shows it as an [object] instead of the CSS class name when used with sx.
For example, I created test case below and the only style that is actually working is 'myBorder' with style prop. sx isn't working. Can anyone shed some light on what I'm doing wrong, newbie here?
import * as React from "react";
const styles = {
myBackground: {
backgroundColor: "red"
},
myBorder: {
border: "2px solid green"
},
myFont: {
color: "blue"
}
};
export default function Index() {
return (
<div
sx={styles.myBackground}
style={styles.myBorder}
classes={styles.myFont}
className={styles.myFont}
maxWidth="sm"
>
This is a test
</div>
);
}
See codepen at https://codesandbox.io/s/mui-5-styling-uqt9m?file=/pages/index.js
Solution 1:[1]
sx only works with MUI component, not HTML element. So you need to replace div. You can use Box instead.
<Box sx={styles.myBackground}>
This is a test
</Box>
For HTML element, use the style attribute, which for your case it's working correctly. For more https://mui.com/system/the-sx-prop/.
Solution 2:[2]
According to the documentation, makeStyles is deprecated and sx is the intended API for design. What about in cases where you need to use an HTML element? I am writing a component that requires "object" for displaying PDFs. So, how would I style this element?
import { Box } from '@mui/material'
export default function Index() {
return (
<Box sx={{
'& object': {
backgroundColor: "red",
border: "2px solid green",
color: "blue",
maxWidth: 'md',
}}}
>
<object/>
</Box>
);
}
In this way, we can indirectly style any HTML element when needed. Since the "Box" component does not introduce any formatting of it's own, that would be the recommended way to implement this technique.
More can be found on this technique: https://mui.com/system/the-sx-prop/#array-values.
Solution 3:[3]
you need to use makeStyles in material UI and you can not use style or classes there :
import * as React from "react";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(() => ({
myBackground: {
backgroundColor: "yellow"
},
myBorder: {
border: "2px solid green"
},
myFont: {
color: "red"
}
}));
export default function Index() {
const styles = useStyles();
return (
<div className={`${styles.myFont} ${styles.myBackground}`} maxWidth="sm">
This is a test
</div>
);
}
it works for me very well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ahadinyoto |
| Solution 2 | cmshnrblu |
| Solution 3 |
