React
[React] ThemeProvider
래모
2022. 7. 9. 18:21
이제는 어디에든 없으면 아쉬운 다크모드!
이건 styled-components를 이용하여 ThemeProvider를 적용해야 한다.
theme 설정
인덱스 파일에 다크모드, 라이트모드 테마의 색들을 설정해준다.
import { ThemeProvider } from "styled-components";
const darkTheme = {
textColor: "whitesmoke",
backgroundColor: "#111",
};
const lightTheme = {
textColor: "#111",
backgroundColor: "whitesmoke",
};
const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(
<React.StrictMode>
<ThemeProvider theme = {darkTheme}>
<App />
</ThemeProvider>
</React.StrictMode>
);
이렇게 설정해주면 다른 파일에서도 theme에 접근해서 색을 이용할 수 있다.
import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
background-color: ${props => props.theme.bgColor};
`
const H1 = styled.h1`
color: ${props => props.theme.textColor};
`
function App() {
return (
<Container>
<H1>Hi</H1>
</Container>
);
}
export default App;


타입스크립트로 적어보자
일단 theme에 들어갈 변수들의 타입을 정해주어야 한다
//style.d.ts
import "styled-components";
declare module "styled-components" {
export interface DefaultTheme {
textColor: string;
bgColor: string;
accentColor: string;
itemBgColor: string;
}
}
이러면 thems.ts에서 DefaultTheme을 import해서 테마에 적용해준다
import { DefaultTheme } from "styled-components";
export const theme: DefaultTheme = {
bgColor: "whitesmoke",
textColor: "black",
accentColor: "#9c88ff",
ItemBgColor: "white",
};
이러면 위랑 똑같이 쓰기 가능~!