Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Typescript with Styled Components and Material UI

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;
`;
like image 511
user10741122 Avatar asked Apr 10 '19 18:04

user10741122


Video Answer


2 Answers

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);
like image 82
Matthieu Dazy Avatar answered Sep 21 '22 07:09

Matthieu Dazy


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;
like image 44
Nathron Avatar answered Sep 17 '22 07:09

Nathron