Home > Enterprise >  React material-ui (MUI) 5 conditional CSS classes
React material-ui (MUI) 5 conditional CSS classes

Time:11-29

I'm moving from React material-ui 4 to MUI 5.

How do I achieve this type of pattern using the new styled API (or whatever makes sense)?

I'm using Typescript. Thank you

const useStyles = makeStyles(theme => ({
    topBar: {
        transition: theme.transitions.create("margin", {
            easing: theme.transitions.easing.sharp,
            duration: TRANSITION_DURATION,
        }),
        marginLeft: DRAWER_WIDTH,
    },
    topBarShift: {
        transition: theme.transitions.create("margin", {
            easing: theme.transitions.easing.easeOut,
            duration: TRANSITION_DURATION,
        }),
        marginLeft: 0,
    },
}));

function Header({ drawer }: IHeader) {
    const classes = useStyles();

    ...

    return (
        <div className={`${classes.topBar} ${!drawer && classes.topBarShift}`}>
           ...
        </div>
    );
}

CodePudding user response:

If I understand your question clearly, you just want a conditional string.

This can be done by creating a util function for reusability:

type ConditionalClasses = {
  [className: string]: bool
}

const conditionalClass = (classes: ConditionalClass) => 
  Object.keys(classes).reduce((combinedClassName, className) => classes[className] ? `${combinedClassName} ${className}` : combinedClassName, "")

Usage goes as follows

// Output: "a"
const newClassName = conditionalClasses({a: true, b: false})

Alternatively, you could use clsx

-- Edit

Looks like I misread and hence misunderstood the question.

If you want to use the styled API styles conditionally, you can use the overridesResolver option provided by the styled API.

const CustomDivComponent = styled("div", {
  overridesResolver: (props, styles) => {
    // Do your conditional logic here.
    // Return the new style.
    return {};
  }
})(({ theme }) => ({
  // Your original styles here...
}));

More documentation can be found here

  • Related