Material ui emotion/styled how to combine multiple snippets of css classes?

Viewed 188

In the old way material ui (version 4 and earlier) styled components you could use className property to "Select" which styles are active, ie a component could be styled like:

const styles = (theme: ThemeTy) => ({
    root: {
        width: '100%',
    },
    rootLight: {
        color: theme.palette.getContrastText(theme.palette.primary.main),

    },
})
const useStyles = makeStyles(styles);

function MyComp() {
    const classes = useLocalStyles();
    return <Input
        className=classNames(classes.root, highContrast ? classes.rootLight : undefined)}
        value={100}
    />
}

However in the new api one would define the classes outside the component similar to styled-components does it:

const StyledInput = styled(Input)(({theme}) => `
    width: '100%',
`);
function MyComp() {
    return <StyledInput
        value={100}
    />
}

However how would I add the conditional styling? Would I have to use the sx element? And thus use conditional styling everywhere?

1 Answers

You can pass any props to your StyledInput and then style the component based on them:

const StyledInput = styled(Input)(({ theme, showborders }) => ({
  width: "100%",
  border: showborders ? "3px solid red" : "none"
}));

...
const [showBorders, setShowBorders] = React.useState(false);
  return (
    <Box>
      <StyledInput showBorders={showborders ? 1 : 0} value={100} />
    </Box>
  );

Demo

Related