garronej / tss-react

✨ Dynamic CSS-in-TS solution, based on Emotion

Home Page:https://tss-react.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The right way typing props when using withStyles

undesicimo opened this issue · comments

For instance, if i am styling a component(in this instance, a MUI component), is the the following the only way to remove compile errors? Would love to here about a much elegant way to do this. Thank you in advance

const Tooltip = withStyles<any, {maxWidth?: string; toolTipBackgroundColor?: string}, any>(
  MuiTooltip,
  (_theme, props: {maxWidth?: string; toolTipBackgroundColor?: string}) => ({
    tooltip: {
      backgroundColor: props => props.toolTipBackgroundColor ?? #ffff
      color: 'white',
      fontSize: 12,
      maxWidth: props.maxWidth ? props.maxWidth : undefined,
    },
  })
);

Hi @undesicimo,

If you want just the type level solution it would be:

import MuiTooltip, { type TooltipProps } from "@mui/material/Tooltip";

const MyTooltip2 = withStyles(
	MuiTooltip as React.ComponentType<TooltipProps & { maxWidth?: string; toolTipBackgroundColor?: string }>,
	(_theme, props) => ({
		tooltip: {
			backgroundColor: props.toolTipBackgroundColor ?? "#ffff",
			color: 'white',
			fontSize: 12,
			maxWidth: props.maxWidth ? props.maxWidth : undefined,
		},
	})
);

That being said, I'd be carfull with that, you'll be passing maxWidth and toolTipBackgroundColor props to the Mui components. Those props are not valid props for MuiTooltip, Mui might end up applying them on native component and you might (or might not) end up with bowser warning.
The safe solution is:

const Tooltip = withStyles(
	(props: TooltipProps & { maxWidth?: string; toolTipBackgroundColor?: string }) => {

		const { maxWidth, toolTipBackgroundColor, ...tooltipProps } = props;

		return <MuiTooltip {...tooltipProps} />;
	},
	(_theme, props) => ({
		tooltip: {
			backgroundColor: props.toolTipBackgroundColor ?? "#ffff",
			color: 'white',
			fontSize: 12,
			maxWidth: props.maxWidth ? props.maxWidth : undefined,
		},
	})
);

// Note: You can also use a non anonymous function as first argument of withStyles
(Tooltip as any).displayName = "Tooltip";

It isn't great I know but the withStyles API is; IMOl; a funamentally flawed API, I provide an impmementation for it only to help pepole migrating MUI v4 codebase.
I encourage you to gradually adopt the modern API that is better in every way.

Hope it helps.

The first example you provided could work for us in the meantime, rather than adding the redundant generics like in my example.

Regarding the withStyles API, i definitely agree and feels the same way. The tss-react + codemods have been a godsend and a huge timesaver in the gradual migration of our huge app.
Ive had my eye on tss modern apis. I would love to work with them if time persists. Thank you again

Thank you, I'm happy the polifils are usefull to you!