install styled-components로 installstyled.d.ts 파일 생성..d.ts : 선언 파일(Declaration File))// styled.d.ts
// import original module declarations
import 'styled-components';
// and extend them!
declare module 'styled-components' {
export interface DefaultTheme {
// 이곳에 theme의 props 및 type 정의
textColor: string;
bgColor: string;
}
}
3.src폴더 내 theme.ts 파일 생성 후, theme 속성 정의
// theme.ts
import { DefaultTheme } from "styled-components";
// styled.d.ts(declatations 파일의 props명과 동일하게)
export const lightTheme: DefaultTheme = {
textColor: "black",
bgColor: "white",
};
export const darkTheme: DefaultTheme = {
textColor: "white",
bgColor: "black",
};
index.tsx에서 app 컴포넌츠를 ThemeProvider로 감싸고, 적용할 theme props 입력.// index.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { ThemeProvider } from "styled-components";
import App from "./App";
import { lightTheme, darkTheme } from "./theme";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
</React.StrictMode>
);
App.tsx등 컴포넌츠에서 css 속성을 props.theme.props명으로 설정.// App.tsx
const Container = styled.div`
background-color: ${(props) => props.theme.bgColor};
`;
const H1 = styled.h1`
color: ${(props) => props.theme.textColor};
`;
function App() {
return (
<Container>
<H1>Protected</H1>
</Container>
);
}
export default App;