Home > Enterprise >  How to override CSS classes made with makeStyles
How to override CSS classes made with makeStyles

Time:07-14

Note, I'm using MUI 4.12.3. In file A I have this (simplified) besides a functional component. Inside the functional component's return statement I also apply it to a JSX element (not shown). This works well.

const useStyles = makeStyles((t) => ({
  content: {
    minHeight: '100vh',
  },
}));

In file B, I would like to override the CSS class content based on isDesktop. Is this possible/desirable? Something like this, but it does not work:

const useStyles = makeStyles({
content: {
    minHeight: (props) => (props.isDesktop ? '100vh' : '112vh'),
  },
});

//And inside my functional component:
const isDesktop = useMediaQuery(Theme.breakpoints.up('sm'));
const classes = useStyles({ isDesktop });

Note that the intent is to not render the JSX component in file B, only to override the CSS class content in file B is desirable. (classes is unused in my sample.)

CodePudding user response:

This can be done with few hooks.Let say my functional componet name is "Mycomponent".my material component is "materialcomponent".we need to import useWindowSize hook.That helps us to get the window size.so that we can check our screen size is desktop or mobile.in the makestyle we have to create two classes for desktop and mobile minHeight.with the simple if else checking we can pass this two classes conditionally to materialcomponent className prop.Below is the code.

1.create two classes with the makestyles

const useStyles = makeStyles((t) => ({
  contentDesktop: {
    minHeight: '100vh',
  },
contentMobile:{
 minHeight: '110vh',
}

}));

2.import the useWindowSize hook

import useWindowSize from "hooks/useWindowSize";

3.functinal componet code.

const Mycomponent = () => {

  const classes = useStyles();
  let my;
  const width = useWindowSize();
  const isDesktop = width >=1024;
  const mobile= width <= 600;

if(isDesktop){

myclass=classes. contentDesktop;

}
if(mobile){
myclass=classes.contentMobile;
}


return (
 
<materialcomponent className={`${myclass}`}

);


}

CodePudding user response:

You can export this function outside of your functional component

export const getStyles = (isDesktop) => {
  return {
    content: {
      minHeight: isDesktop ? "100vh" : "112vh",
    },
  };
};

And then wherever you want your styling applied

const isDesktop = useMediaQuery(Theme.breakpoints.up('sm'));

...
  <SomeMuiComponent sx={getStyles(isDekstop)} />
  • Related