Styled-Components-Typescript-Example icon indicating copy to clipboard operation
Styled-Components-Typescript-Example copied to clipboard

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

Open IanEdington opened this issue 7 years ago • 2 comments

For example the equivalent of something like this:

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

IanEdington avatar Mar 11 '18 19:03 IanEdington

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 };

henck avatar Dec 15 '18 10:12 henck

@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>

antoinerousseau avatar Feb 21 '19 14:02 antoinerousseau