Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save benvium/cf76da5c757e13ec2ee0ce2c37631281 to your computer and use it in GitHub Desktop.
Save benvium/cf76da5c757e13ec2ee0ce2c37631281 to your computer and use it in GitHub Desktop.
Using TypeScript with styled-components 4.1.1 for attrs and styled
import styled from 'styled-components'; // 4.1.1
import * as React from "react";
type SizeProp = { size: number };
const A = styled.div<SizeProp>`
height: ${props => props.size}px;
`;
const Ac = () => <A size={99} />;
// extending - note it has inherited A's SizeProps, so no type annotation needed
const B = styled(A)`
width: ${props => props.size}px;
`;
const Bc = () => <A size={99}/>;
// use in attrs but not CSS body - per prop function style
const C = styled.div.attrs<SizeProp>({
title: (props:SizeProp) => `this is ${props.size}`
})`
width: 33px;
`;
// use in attrs but not CSS body - attrs as single function
const C2 = styled.div.attrs<SizeProp>(props => ({
title: `this is ${props.size}`
}))`
width: 33px;
`;
// use in attrs AND CSS body - per prop function style
const D = styled.div.attrs<SizeProp>({
title: (props:SizeProp) => `this is ${props.size}`
})<SizeProp>`
width: ${props => props.size}px;
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment