简体   繁体   中英

Avoid inline styling - Mui V5

In my opinion seperating styling from code makes the code clearer and cleaner. Using inline styling ( style={{}} ) has been considered a bas practice for me.

In Mui V4 is was easy - I've just created a styles file and imported it to my component code using makeStyles() and useStyles() hooks.

Now with the new sx prop in Mui V5 I have no idea how to avoid inline styling. Any ideas?

You can do something similar with sx too. Create a new styles file and define your objects there. Just use them in the sx attribute:

styles.ts:

const gridStyles = {
  backgroundColor: "blue",
  paddingBottom: 2,
  paddingRight: 2,
  marginTop: 2,
  marginLeft: "auto",
  marginRight: "auto",
  maxWidth: 500
};
export default gridStyles;
import gridStyles from './styles';

export default function FullWidthGrid() {
  return (
    <>
      <Grid
        container
        sx={gridStyles}
      </Grid>
  );
}

to respond to @Yahli Gi, if u want to access the theme, there's two ways:

Method one:

const gridStyles = (theme) => ({
  backgroundColor: "blue",
  paddingBottom: 2,
  paddingRight: 2,
  marginTop:theme.spacing(1),
  marginLeft: "auto",
  marginRight: "auto",
  maxWidth: 500
});

export default gridStyles;

Method Two:

const gridStyles = {
  backgroundColor: "blue",
  paddingBottom: 2,
  paddingRight: 2,
  marginTop: (theme) => theme.spacing(1),
  marginLeft: "auto",
  marginRight: "auto",
  maxWidth: 500
};

export default gridStyles;

The imports are the same for the two examples above. Additionally the theme is automatically injected into the object by mui so no need to call the function yourself in the import.

import gridStyles from './styles';

export default function FullWidthGrid() {
  return (
    <>
      <Grid
        container
        sx={gridStyles}
      </Grid>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM