Home > Net >  React Material UI v5 styled with TypeScript
React Material UI v5 styled with TypeScript

Time:03-18

Styled typography accepts all the default typography props. When I add <ExtraProps> between styled() and the style, it also accepts extra props.

const StyledTypography = styled(Typography)<ExtraProps>({})

My question is: when I render the styled typography component with prop "component" or "as" it does not accept the dynamic component props.

example:

<StyledTypography component={Link} to="/test">demo</StyledTypography>

(Link is from react-router-dom)

It can not find the prop "to" that comes from "Link" component and that makes error. The default Typography accepts component argument Typography<Link>, but the one that extends the default Typography with styled does not.

How to make the styled component accept the new props that come from the dynamic component.

(I know that prop as={(props) => <Link to="/test" {...props} /> works, but I do not want it to be like this. It has to be as={Link} and to="/test")

CodePudding user response:

This

styled(Typography)({}) as typeof Typography | FC<ExtraProps>

or this

const StyledTypography: (typeof Typography | FC<ExtraProps>) = styled....

works fine.

But it does not feel like the best answer. There should be a better one

CodePudding user response:

Try something like this:

const [toogle, seToggle] = useState(flase);

const StyledTypography = styled(Typography)({

background-color: ${(props) =>

   (props?.cardToggle ? 'lightgrey' : 'white')};

})`

<StyledTypography onclick={()=> setToggle(!toggle)} cardToggle={toggle} component={Link} to="/test">demo</StyledTypography>
  • Related