question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How override Mui v5 styles with makeStyles?

See original GitHub issue

Hello,

Three days ago I migrated from version 4 to 5. I use makeStyles to style all my components. But with version 5, many of my styles have lost priority and the original mui styles win over my styles with makeStyles. I’ve been reading a lot about this problem and I don’t understand which is the best solution for now. I tried with StyledEngineProvider of course, but my problem persists.

I use SSR in my app, but I have here a simple example to see this: https://codesandbox.io/s/hook-material-demo-forked-l7wwu

The visual example: 2021-09-28_12h51_37

The priority now: 2021-09-28_12h54_47

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:8
  • Comments:20 (8 by maintainers)

github_iconTop GitHub Comments

12reactions
Hillsiecommented, Oct 1, 2021

@mnajdova, I want to let you know that I really appreciate what MUI provides the community. It’s a really helpful product. I also want to make you aware that @jlramosr is not the only dev finding the version upgrade challenging. Upgrading from 4 to 5 has been days. Management does not want to be locked into V4 at the beginning of a new project. As you can image, I don’t have the luxury nor time to upgrade older code to the new MUI styling methods, nor upgrade older code that uses a different styling system. It’s been a stressful upgrade having to explaining delays.

With the first attempt, I followed the online guide step by step, but couldn’t stand up the code. There were too many changes and I couldn’t identify the source of the issues. Our code base uses styling aspects MUI 5 no longer recommended or supported. Based on previous coders and learning the system, in some cases, it’s unconventional.

With the second attempt, I resorted doing it manually… (mostly).

Hopefully my summary helps … to a point, @jlramosr. This is based on my understanding and may not all be valid, but worked so far.

Foundation upgrade:

  1. Updated to latest version of node and npm. npm install -g npm@latest. see node.org or nvm for the latest node install.
  2. npm audit fix -force (npm errors out if there are any unmaintained packages in the tree)
  3. npm dedup --force
  4. npm install react@17.0.0 react-dom@17.0.0 --force (used force as it was erroring based on older package dependencies.)
  5. Manually went through package.json and updated to most current version of all packages based on npm versions.
  6. npm update --force (have legacy code scheduled to be updated in the future).
  7. npm install @mui/material @mui/styles --force (mui errors if there are legacy dependencies in the tree)
  8. npm install @mui/icons-material --force

Code changes:

Component example:

import React from "react";
import makeStyles from "@mui/styles/makeStyles";
import Container from "@mui/material/Container";
import Typography from "@mui/material/Typography";

const useStyles = makeStyles((theme) => ({
  header: {
    backgroundImage: ({ image }) =>
      `linear-gradient(rgb(56, 40, 126, 0.2),rgb(56, 40, 126, 0.2)), url(${image})`,
      opacity:1,
    backgroundPosition: "center",
    backgroundSize: "cover",
    height: ({ headerHeight }) =>
      headerHeight ? headerHeight : "calc(70vh - 68px)",
    [theme.breakpoints.only("md")]: {
      height: 400,
    },
    [theme.breakpoints.only("sm")]: {
      height: 300,
    },
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  },
  container: {
    [theme.breakpoints.down("xl")]: {
      maxWidth: ({ maxTextWidth }) => maxTextWidth,
    },
    [theme.breakpoints.down('lg')]: {
      maxWidth: ({ maxMobileTextWidth }) => maxMobileTextWidth,
    },
  },
  headline: {
    fontWeight: "600",
    textAlign: "center",
    color: theme.palette.common.white,
  },
}));

const BasicPageHeader = ({
  image,
  headerText,
  headerHeight,
  maxTextWidth,
  maxMobileTextWidth,
}) => {
  const classes = useStyles({
    image,
    headerHeight,
    maxTextWidth,
    maxMobileTextWidth,
  });
  return (
    <div>
      <div className={`${classes.header}`}>
        <Container classes={{ root: classes.container }}>
          <Typography
            variant="h3"
            component="h1"
            classes={{ root: classes.headline }}
          >
            {headerText}
          </Typography>
        </Container>
      </div>
    </div>
  );
};

BasicPageHeader.defaultProps = {
  image: undefined,
  headerHeight: undefined,
  maxMobileTextWidth: "20rem",
  maxTextWidth: "60rem",
  headerText: "xyz,
};

export default BasicPageHeader;

Had to use the breakpoints private method in theme code. Unsure if this has an impact in createBreakpoints, but have to retrofit breakpoints so MUI 5 upgrade does not impact current layout. Overrides don’t work in the theme. Still figuring this out. Layout changes in the breakpoints caused all sorts of issues in the current code base. So added the breakpoints back.

import { createTheme, adaptV4Theme} from "@mui/material/styles"; import createBreakpoints from "@mui/system/createTheme/createBreakpoints";

const breakpoints = createBreakpoints({
  xs: 0,
  sm: 600,
  md: 960,
  lg: 1280,
  xl: 1920,
});

Not everything works below. Overrides are different in MUI 5.0

const theme = createTheme(
  adaptV4Theme({
    overrides: {
      MuiCssBaseline: {
        "@global": {
          a: {
            textDecoration: "none",
            "&:hover": {
              textDecoration: "none",
            },
          },
        },
      },
    },
    breakpoints: {
      values: {
        xs: 0,
        sm: 600,
        md: 960,
        lg: 1280,
        xl: 1920,
      },
    },
    props: {
      MuiButtonBase: {
        disableRipple: true,
      },
    },
    palette: {
      common: {
        ...
      },
      ...
    },
    typography: {
      fontFamily: [
        "Roboto",
      .....
      ].join(","),
      tab: {},
      h1: {},
      h2: {},
      h3: {
        [breakpoints.down("md")]: {
          fontSize: "2rem",
        },
      },
     \
    zIndex: {
      appBar: 20,
    },
  })
);

export default theme

Finally, the code ran again, but then realised all the breakpoints did not work. useStyles breakpoints caused issues. Layout is different.

Nearly gave up

As a final attempt before I was going to tell management, I failed, I ran the codemode.

npx @mui/codemod --dry --print v5.0.0/preset-safe ./src Inside the project root.

npx @mui/codemod v5.0.0/preset-safe ./src

This worked and did some magic, unlike the first experience.

Last breaking changes I need to resolve

The style overrides in useStyles are not working in many dynamic components. As far as I know, this impacts Tabs, Accordions and SVG Icons. Currently, I’m stuck here.

Final thoughts

Although you have rebranded to MUI, being associated with Material-UI has been a good thing. It’s given MUI associated branding Google’s Material Design, which has been a positive for your brand.

Not all upgrades are on greenfield projects.

This upgrade has not been easy and is still not done.

4reactions
ajbosleyZonecommented, Oct 7, 2021

@Hillsie Thanks for your lengthy explanation of what you’ve had to go through.

I also followed the migration guide and currently cannot stand my project up. I’m also having issues with useStyles and makeStyles, I will look at what you’ve done here in the hope it can fix my issues.

I’m expecting to rewrite our entire theming system which will be laborious and require a considerable test effort from our QA and design teams to confirm everything is back as it should be.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Overriding existing Mui classes using makeStyles
To override these styles, you do it via overriding styles with classes. ... Create the class name and add the styling in makeStyles...
Read more >
Breaking changes in v5, part one: styles and themes - MUI
This is a reference guide to all of the breaking changes introduced in Material v5, and how to handle them when migrating from...
Read more >
Material UI 5 - the easiest way to migrate from makeStyles to ...
Good one. To people setting up brand new MUI v5 projects in 2021, the official way to override default styles now is through...
Read more >
4 Ways to Override Material UI Styles | by John Au-Yeung
Understanding the 4 methods for overriding styling in Material UI StyleProvider, ... We also have to use makeStyles to create styles.
Read more >
Material UI v.5 Tutorial | How to Style and Customize | Part 3
We will have a look at what Material UI ( MUI ) is and how you can use it in your projects. In...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found