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;
`;
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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With