📚Theme
- styled-components 테마와 Typescript를 연결해야 한다.
📌모듈 설치하기
📌declarations 파일 만들기
- 다음으로 src 폴더에
styled.d.ts
라는 파일명을 가진 파일을 생성한다. 이 파일은 우리가 이전에 설치해 놓은 파일들을 overwrite 하는 것이다. 테마에 사용할 타입들을 포함시키고 싶은 것이니까
styled.d.ts
에 하단의 코드를 복붙한다.
import "styled-components";
declare module "styled-components" {
export interface DefaultTheme {
borderRadius: string;
colors: {
main: string;
secondary: string;
};
}
}
declare module "styled-components" {
export interface DefaultTheme {
textColor: string;
bgColor: string;
btnColor: string;
}
}
📌theme 만들기
- 먼저
theme.ts
파일을 만든다. 이 파일에는 declartions 파일에 정의했던 속성들과 같아야한다.
- 라이트테마, 다크테마를 만들것이다.
import { DefaultTheme } from "styled-components";
export const lightTheme: DefaultTheme = {
bgColor: "white",
textColor: "black",
btnColor: "tomato",
};
export const darkTheme: DefaultTheme = {
bgColor: "black",
textColor: "white",
btnColor: "teal",
};
📌ThemeProvider setting
index.tsx
에 와서 ThemeProvider를 import하고 코드에 추가한다.
- ThemeProvider는 styled-components로부터 오는 하나의 컴포넌트이다. 따라서 ThemProvider 안에 컴포넌트를 넣게 된다면 안에 있는 컴포넌트들은 Theme 객체에 접근할 수 있다.
- lightTheme를 설정한다면 아래와 같이 코드를 작성한다.
import React from "react";
import ReactDOM from "react-dom";
import { ThemeProvider } from "styled-components";
import App from "./App";
import { lightTheme } from "./theme";
ReactDOM.render(
<React.StrictMode>
<ThemeProvider theme={lightTheme}>
<App />
</ThemeProvider>
</React.StrictMode>,
document.getElementById("root")
);
📌theme 적용하기
- ThemeProvider 안에 있는 컴포넌트인 App 컴포넌트에서 정의해두었던 Theme을 사용해보자.
const Container = styled.div`
background-color: ${(props) => props.theme.bgColor};
`;
const H1 = styled.h1`
color: ${(props) => props.theme.textColor};
`;
참고 : styled-components document