Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled-components defaultProps

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?

like image 888
donzul Avatar asked Sep 07 '18 16:09

donzul


1 Answers

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}/>;
  }
}
like image 140
Matt McCutchen Avatar answered Oct 27 '22 09:10

Matt McCutchen