스타일 컴포넌트의 테마에 사용될 변수 타입을 선언하기 위한 파일이다.
보통 자주 사용하는 css를 변수로 등록한다.
styled-components 모듈에 defaultTheme라는 인터페이스 내부에 타입을 선언한다.
import "styled-components"
declare module "styled-components" {
export interface DefaultTheme {
textColor : string;
bgColor : string;
}
}
defaultTheme 인터페이스를 import 및 타입을 준수하여 테마를 작성한다.
import { DefaultTheme } from "styled-components/dist/types";
export const DarkTheme : DefaultTheme = {
textColor : "white",
bgColor : "black"
}
export const LightTheme : DefaultTheme = {
textColor : "black",
bgColor : "white"
}
ThemeProvider의 하위 컴포넌트는 theme.ts의 영향을 받아 props에서 css 값을 가져올 수 있다.
-App.tsx
import { styled, ThemeProvider } from 'styled-components';
import { LightTheme, DarkTheme } from './theme';
const Wrapper = styled.div`
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: ${(props) => props.theme.bgColor};
`
const Title = styled.h1`
font-size: 5rem;
color : ${(props) => props.theme.textColor};
`;
const App = () => {
return (
<ThemeProvider theme={DarkTheme}>
<Wrapper>
<Title>Hello!</Title>
</Wrapper>
</ThemeProvider>
)
}
참고