5

Using Typescript with MUI+Styled-Components and you have to directly pass props to MUI elements due to type errors….

const Index = () => {
  return (
      <StyledButton
        variant="contained"
      >
        Hello World
      </StyledButton>
   )}


const StyledButton = styled(Button)`
  background: red;
  color: white;
`;

However, this will error the following:

Type '{ children: string; variant: "contained"; }' is not assignable to type '(IntrinsicAttributes & Pick>) | PropsWithChildren, "form" | "style" | "title" | ... 284 more ... | "variant"> & Partial<...>, "form" | ... 286 more ... | "variant"> & { ...; } & { ...; }) | (IntrinsicAttributes & ... 3 more ... & { ...; })’

When you directly pass in props such as below, then this error goes away. Even using 0 props and 0 children on the Styled MUI element, it gives the error.

const StyledButton = styled(props => <Button {...props} />)`
  background: red;
  color: white;
`;

2 Answers 2

5

This should work fine with MUI >= 4.*

For earlier versions, from this tutorial, try enforcing the type of StyledButton:

const StyledButton = styled(Button)`
  background: red;
  color: white;
` as typeof Button;
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! it should actually be: as typeof Button instead
3

I accidentally solved this by installing @types/styled-components / styled-components, which I required anyways to get styled/theme/TS all playing nicely together:

import React from "react";
import styled from "styled-components";
import { Theme, useTheme } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

const StyledCustomButton: React.FC<{
  theme: Theme;
}> = styled(({ ...props }) => <Button {...props}>Test</Button>)`
  && {
    padding-bottom: ${(props) => props.theme.spacing(2)}px;
  }
`;

const CustomButton: React.FC = () => {
  const theme: Theme = useTheme();
  return <StyledCustomButton theme={theme} />;
};

export default CustomButton;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.