Conditionally add styles properties on MUI

Viewed 720

On styled-components we can have something like this

import syled, { css } from 'styled-components';
const StyledButton = styled.button<StyledButtonProps>`
    display: flex;
    ${textStyles.styledButton}
    ${props =>
        props.disabled &&
        css`
            opacity: 0.5;
        `}
`

I'm trying to use MUI's styled but can't find how to conditionally add the opacity property based on the props passed to the button. I'm trying something like this, but don't want to define the default value of every conditional styles as on opacity here (since there could be a LOT of conditional properties based on the value of a passed prop)

import { styled } from '@material-ui/core/styles';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const StyledMUIButton = styled(({ disabled, disclosure, whiteButton, fullWidth, noMarginTop, ...rest }: StyledButtonProps) => (
    <button {...rest} />
))({
    display: 'flex',
    ...textStyles.button,
    opacity: (props: StyledButtonProps) => props.disabled ? 0.5 : 1
})

Another case would be something like this in styled-components, how can be that applied to MUI's styled?


    ${props =>
        props.whiteButton
            ? css`
                  background-color: transparent;
                  border: none;
                  ${textStyles.styledLink}
              `
            : css`
                  &:focus {
                      background: transparent;
                      border: 1px solid ${colors.textLink};
                      color: ${colors.textLink};
                  }
              `}
1 Answers

I ended up using makeStyles the following way

const useStyles = makeStyles({
    button: (props: StyledButtonProps) => ({
        display: 'flex',
        ...textStyles.button,
        ...props.disabled && { opacity: 0.5 },
    })
})
Related