withStyles
It's like the material-ui v4 higher-order component API but type safe by design.

import { withStyles } from "tss-react/mui";
type Props = {
className?: string;
classes?: Partial<Record<"root" | "text", string>>;
colorSmall: string;
};
function MyComponent(props: Props) {
const classes = withStyles.getClasses(props);
return (
// props.classeName and props.classes.root are merged, props.className get higher specificity
<div className={classes.root}>
<span className={classes.text}>The background color should be different when the screen is small.</span>
</div>
);
}
const MyComponentStyled = withStyles(
MyComponent,
(theme, props) => ({
root: {
backgroundColor: theme.palette.primary.main,
height: 100
},
text: {
border: "1px solid red"
},
"@media (max-width: 960px)": {
root: {
backgroundColor: props.colorSmall
}
}
})
);
export default MyComponentStyled;If you have your styles defined as a separate function:
The main reason you would use withStyles over makeStyles is to support class based components.
Or, if you have your styles defined as a separate function:
With no classes props
Your component can also only have a className prop (and no classes).
With a MUI component
You can also pass a mui component like for example <Button /> and you'll be able to overwrite every rule name of the component (it uses the classes prop).
What's very powerfull about the withStyles API it it's capable to infer the type of the nested overwritable classes, example:

With an base HTML component
You can experiment with those examples here live here, you can also run it locally with yarn start_spa.
Naming the stylesheets (useful for debugging and theme style overrides)
To ease debugging you can specify a name that will appear in every class names. It is like the option.name in material-ui v4's makeStyles.
It's also required to for theme style overrides.
Use in place of styled
If you want to use withStyles instead of styled for the extra type safety it provides:
Before:
After (just wrap everything into root):
Last updated
Was this helpful?
