Yahli Gitzi
Yahli Gitzi

Reputation: 569

MUI v5 - Seperate styling from component file

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?

Upvotes: 13

Views: 12892

Answers (3)

Stephen Melben Corral
Stephen Melben Corral

Reputation: 319

I would recommend CSS Modules or Plain CSS because the other styling solution might get deprecated in the near future, one good example is the makeStyle which is now considered a Legacy styling solution.

You can find more information in Mui's webpage under the Style library interoperability section.

Upvotes: 2

NearHuscarl
NearHuscarl

Reputation: 81783

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]}`,
          },
        },
      ],
    },
  },
});

Upvotes: 15

Tony Yip
Tony Yip

Reputation: 750

It is suggested to use either sx or styled.

Document: https://mui.com/system/basics/

Upvotes: 0

Related Questions