0

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.

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>
    );
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

With material-ui 5 makeStyles() has been replaced with styled(). Was looking for the new equivalent.
@TyKroll I looked at the documentation makeStyles hasn't been replaced (or deprecated for that matter). If you're talking about using moving away from jss, as described here, let me know and I'll adjust my answer.
@TyKroll new answer should be what you're looking for, let me know though :)
@TyKroll did this answer your question? If so, please mark it as approved :) If not, please let me know there's any clarification to be made.
I decided to totally rewrite from scratch so didn't need the above approach. It is indeed the correct answer regardless. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.