1. 라이브러리 설치
npm install --save-dev @types/styled-components
2. declaration file : styled.d.ts 생성
// import original module declarations
import 'styled-components';
// and extend them!
declare module 'styled-components' {
export interface DefaultTheme {
borderRadius: string;
colors: {
main: string;
secondary: string;
};
}
}
3. theme 생성
//my-theme.ts
import { DefaultTheme } from 'styled-components';
const myTheme: DefaultTheme = {
borderRadius: '5px',
colors: {
main: 'cyan',
secondary: 'magenta',
},
};
export { myTheme };
4. styling components
import styled, { createGlobalStyle, css } from 'styled-components';
//Component
export const MyComponent = styled.div`
color: ${props => props.theme.colors.main};
`;
//Global style
export MyGlobalStyle = createGlobalStyle`
body {
background-color: ${props => props.theme.colors.secondary};
}
`;
//CSS
export cssHelper = css`
border: 1px solid ${props => props.theme.borderRadius};
`;
5. Using custom props
import styled from 'styled-components';
import Header from './Header';
interface TitleProps {
readonly isActive: boolean;
}
//interface나 내부 타입지정을 사용
const Title = styled.h1<TitleProps>`
color: ${(props) => (props.isActive ? props.theme.colors.main : props.theme.colors.secondary)};
`;
const NewHeader = styled(Header)<{ customColor: string }>`
color: ${(props) => props.customColor};
`;
//Header가 props.$customColor를 받지 않게 할 때
const NewHeader2 = styled(Header)<{ $customColor: string }>`
color: ${(props) => props.$customColor};
`;
//custom props 활용
import styled from 'styled-components';
import Header, { Props as HeaderProps } from './Header';
const NewHeader3 = styled(({ customColor, ...rest }: { customColor: string } & HeaderProps) => <Header {...rest} />)`
color: ${(props) => props.customColor};
`;
//shouldForwardProp 활용
import styled from 'styled-components';
import Header from './Header';
const NewHeader4 = styled(Header).withConfig({
shouldForwardProp: (prop, defaultValidatorFn) => !['customColor'].includes(prop),
})<{ customColor: string }>`
color: ${(props) => props.customColor};
`;
6-1. 주의사항 - className
interface LogoProps {
className?: string; //-> optional하게 : TS가 체크 못함
}
class Logo extends React.Component<LogoProps, {}> {
render() {
return <div className={this.props.className}>Logo</div>;
}
}
const LogoStyled = styled(Logo)`
font-family: 'Helvetica';
font-weight: bold;
font-size: 1.8rem;
`;
6-2. 주의사항 - Function Components
interface BoxProps {
theme?: ThemeInterface;
borders?: boolean;
className?: string;
}
const Box: React.FunctionComponent<BoxProps> = (props) => <div className={props.className}>{props.children}</div>;
const StyledBox = styled(Box)`
padding: ${(props) => props.theme.lateralPadding};
`;