What is the best way to use sx prop in MUI v5?

Viewed 1748

I have started using MUI v5 with makeStyles in my previous project. After deploying, I faced a huge delay in loading page's CSS. So I started searching that found out makeStyles is deprecated in MUI v5.

MUI suggests to use sx prop instead. That's fine. But the problem here is I don't want to write my JSX and CSS/JSS code together. For example:

This is what MUI says:

// App.js
function App() {
  return (
    <Grid sx={{ bgcolor: 'yellow', mx: 5, pt: 2, border: 1 }}>
      This is a test!
    </Grid>
  );
}

export default App;

Below is somehow what I expect:

// style.js
export default {
  myGrid: {
    bgcolor: 'yellow',
    mx: 5,
    pt: 2,
    border: 1,
  },
};
// App.js
import style from "./style";

function App() {
  return <Grid sx={style.myGrid}>This is a test!</Grid>;
}

export default App;

I wanna know what is the best pattern to use JSS and JSX files independently with sx? Is it possible to get VSCode suggestions while typing sx props in another file?

1 Answers

You can achieve this with TypeScript. If TypeScript is not already configured in your project, you would have to add it (see this SO answer for help with that).

Then you can make a styles.ts file with all of your component styles by using the SxProps type.

// Styles.ts
import { SxProps } from '@mui/material'

const myGrid: SxProps = {
  bgColor: 'yellow',
  mx: 5,
  pt: 2,
  border: 1
}

export default { myGrid }

By using the SxProps type on your stlye object, you'll get code completion with all of the MUI sx props.

Related