I want to separate styling from component File in MUI v5. The way I did it in v4 was using makeStyles
like that:
Page.style.js
:
import { makeStyles } from "@material-ui/core";
export const useStyles = makeStyles({
root: {
background: "white",
},
});
Page.js
:
import React from "react";
import useStyles from "./Page.style";
const Page = () => {
const classes = useStyles();
return (
<div className={classes.root}></div>
)
}
makeStyles
is now legacy and I heard it will be deprecated next version.
What is the proper way to separate styling and component into different files in v5?
CodePudding user response:
The recommended styling APIs in v5 are styled()
/sx
prop. If you use styled
, you can separate the styling code by creating a reusable styled component. The sx
prop is more suitable for inline one-off style so it's not the best choice to use in this scenario:
const Div = styled('div')({
background: "white",
});
export Div;
import React from "react";
import { Div } from "./Div";
const Page = () => {
return (
<Div />
)
}
Besides that, you can also use variant in MUI v5. The way it works is you create a custom styles and assign a name for it called variant so instead of specifying a className like before, you set the variant
prop like this:
<Button variant="myCustomVariant">
Button
</Button>
Custom variant can be created using createTheme
. See this answer for more detail. Be aware that for now, this feature is not supported in all components:
const theme = createTheme({
components: {
MuiButton: {
variants: [
{
props: { variant: 'myCustomVariant' },
style: {
textTransform: 'none',
border: `2px dashed grey${blue[500]}`,
},
},
],
},
},
});
CodePudding user response:
It is suggested to use either sx
or styled
.
Document: https://mui.com/system/basics/