theme는 모든 색상을 가지고 있는 object를 말한다.
보통 다크모드를 구현하기 위해 사용된다.
색상을 바꿀때는 object만 바꿔주면 되는 것이다.
theme를 사용하기 위한 작업은 보통 index.js 파일에서 이루어진다.
import { ThemeProvider } from 'styled-components';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ThemeProvider>
<App />
</ThemeProvider>
);
const darkTheme = {
textColor : "white",
bgColor : "black"
}
const whiteTheme = {
textColor : "black",
bgColor : "white"
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
);
위 절차가 끝나면 theme 사용을 위한 세팅은 완료되었다고 볼 수 있다.
설정한 테마를 사용하려면 어떻게 해야할까?
App 컴포넌트는 ThemeProvider 내부에 속해있기 때문에 App 컴포넌트에서 theme에 접근할 수 있다.
상위 컴포넌트에서 전달한 theme object에 접근해 속성값에 접근하여 사용할 수 있는 것이다.
사용 방법은 스타일 컴포넌트에서 prop을 사용하는 것과 유사하다.
-Index.js
const darkTheme = {
textColor : "white",
bgColor : "black"
}
const whiteTheme = {
textColor : "black",
bgColor : "white"
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
);
-App.js
const Wrapper = styled.div`
background-color: ${(props) => props.theme.bgColor};
display: flex;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
`
const Title = styled.h1`
color : ${(props) => props.theme.textColor};
font-size: 5rem;
`;
const App = () => {
return (
<Wrapper>
<Title>Hello!</Title>
</Wrapper>
)
}

테마를 변경한다하면 굳이 색상을 변경해줄 필요 없이 theme props만 변경해주면 된다.
유의할 점은 사용하는 theme 객체들의 키값만 서로 같으면 된다.
최종 정리하면 설정한 테마에 따라 지정한 색상을 props로 전달받아 사용할 수 있다.
다만 프로젝트의 규모가 커질 경우 별도의 경로에서 theme를 관리하는 것이 유지보수 측면에서 편리할 것이라는 생각이 들었다.
참고