patrick91 / Styled-Components-Typescript-Example

Sample "app" using typescript and styled components.
104 stars 27 forks source link

Can we get an example of using Typescript with props other than theme? #5

Open IanEdington opened 6 years ago

IanEdington commented 6 years ago

For example the equivalent of something like this:

const SomeComponent = styled.div`
  visibility: ${props => props.visible ? 'visible' : 'hidden'};
  ${props => props.margin && `margin: ${props.margin}`};
`;
henck commented 5 years ago

Is this what you are looking for?

import * as React from "react";
import styled from "../theme";

interface ISomeComponentProps {
  className?: string;
  visible?: boolean;
  margin: number;
}

class SomeComponentBase extends React.Component<ISomeComponentProps, {}> {
  render() {
    return <div className={this.props.className}>{this.props.children}</div>;
  }
}

const SomeComponent = styled(SomeComponentBase)`
  visibility: ${props => props.visible ? 'visible' : 'hidden'};
  ${props => props.margin && `margin: ${props.margin}px`};      
`;

export { SomeComponent };
antoinerousseau commented 5 years ago

@henck can this be done without having to write that SomeComponentBase and just use styled.div?

Edit: I understand now that this wouldn't be ideal because TS complaining here forces us to not pass the prop as an actual DOM attribute, which might actually be good.

I ended up with:

const Div = ({visible, children, ...props}) => <div {...props}>{children}</div>

Or if you don't need dynamic attributes:

const Div = ({children}) => <div>{children}</div>