If I have the following button with a defaultProp
export interface IButton {
variant: 'action' | 'secondary';
}
export const Button = styled('button')<IButton>`
background-color: #fff;
${props =>
props.variant === 'action' &&
css`
color: blue;
`};
${props =>
props.variant === 'secondary' &&
css`
color: gray;
`};
`;
Button.defaultProps = {
variant: 'action',
};
Is there a way to type it? When trying to use it like
<Button>Hello</Button>
Typescript complains about not passing variant, is there a way to type defaultProps with styled components?
The problem is that TypeScript 3.0's support for defaultProps
in checking JSX elements requires the type of the defaultProps
to be declared on the component. Mutating the defaultProps
of an existing component won't work, and I'm not aware of any good way to declare the defaultProps
on a component generated by a function like styled
. (In a way, this makes sense: the library creates a component and doesn't expect you to modify it. Maybe the library even sets defaultProps
itself for some internal purpose.) kingdaro's solution is fine, or you can use a wrapper component:
const Button1 = styled('button')<IButton>`
background-color: #fff;
${props =>
props.variant === 'action' &&
css`
color: blue;
`};
${props =>
props.variant === 'secondary' &&
css`
color: gray;
`};
`;
export class Button extends React.Component<IButton> {
static defaultProps = {
variant: 'action'
};
render() {
return <Button1 {...this.props}/>;
}
}
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