For (typescript + styled-components…)
ts에게 styled-component가 무엇인지 설명해야함
→ npm i --save-dev @types/styled-components
declaration (선언) 파일 만들기 (FileName.d.ts)
→ theme을 만들어야하므로 확장할 필요가 있음 → styled.d.ts 만들기 [이전에 설치한 파일 override]
//styled.d.ts
//styled.d.ts override
import 'styled-components';
//styled-components의 theme 정의를 확장
declare module 'styled-components' {
export interface DefaultTheme {
textColor : string;
bgColor : string;
};
}
}
styled.d.ts에서 확장한것을 가져와서 정의
//theme.ts
//styled.d.ts에서 styled-components의 theme을 확장 시킨것을 가져옴
import { DefaultTheme } from "styled-components";
//DefaultTheme을 확장하여 darkTheme과 lightTheme을 정의
const darkTheme: DefaultTheme = {
textColor: "whitesmoke",
bgColor: "#111",
};
const lightTheme: DefaultTheme = {
textColor: "#111",
bgColor: "whitesmoke",
};
export { darkTheme, lightTheme };
ThemeProvider에 theme object 넣기
//index.tsx
import { darkTheme, lightTheme } from "./theme";
import { ThemeProvider } from "styled-components";
import App from "./App";
import React from "react";
import ReactDOM from "react-dom/client";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
//ThemeProvider에 theme object를 넣어줌
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
);
정의한 theme을 사용하기
//App.tsx
import styled from "styled-components";
//theme에 정의된 bgColor, textColor을 props로 가져와서 사용
const Container = styled.div`
background-color: **${(props) => props.theme.bgColor};**
color: **${(props) => props.theme.textColor};**
`;
export default function App() {
return <Container>Hello world</Container>;
}