3 번에서 자세히 다뤄보겠당
Styled Components의 Theme과 State Management(Recoil, Redux 등)를 이용하여 구현할 수 있다
Recoil에 대한 글을 작성한 후, 직접 구현하는 글도 올릴 예정이다
보통 index.js 파일에서 작성한다
import { ThemeProvider } from "styled-components";
ReactDOM.render(
<React.StrictMode>
<ThemeProvider theme={}>
<App />
</ThemeProvider>
</React.StrictMode>,
document.getElementById("root")
);
이 때 ThemeProvider에는 위와같이 theme prop이 필수이다
prop에는 사용할 이름과 색을 오브젝트 형식으로 넘겨준다
const darkTheme = {
textColor: "skyblue",
bgColor: "#111",
};
const ligthTheme = {
textColor: "#111",
bgColor: "skyblue",
};
ReactDOM.render(
<React.StrictMode>
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
</React.StrictMode>,
document.getElementById("root")
);
이 때 각 색을 담은 오브젝트에서 색의 이름은 동일하게 해주는게 좋다
왜 그런지 조금더 읽다보면 알 수 있다
위의 과정을 마쳤다면 theme을 사용할 준비는 끝났다고 볼 수 있다
현재 나의 App 컴포넌트는 ThemeProvider로 감싸져 있기 때문에, App 컴포넌트에서 theme에 접근하는 것이 가능하다
사용 방법은 아주아주 간단하다
이전 글에서 styled component안에서 prop을 전달해서 사용했던 방식과 동일하게 사용할 수 있다
const Components = styled.div`
display: flex;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
background-color: ${(props) => props.theme.bgColor};
`;
const Title = styled.h1`
color: ${(props) => props.theme.textColor};
font-size: 36px;
font-weight: 600;
`;
function App() {
return (
<Components>
<Title>Hello World!!</Title>
</Components>
);
}
이 때 props.theme.~~의 ~~는 색상의 이름을 정해둔 오브젝트에서의 이름과 같아야 한다
여기서 ThemeProvider의 theme prop 을
<ThemeProvider theme={darkTheme}>
에서
<ThemeProvider theme={ligthTheme}>
로 바꿔보자
위 처럼 단 한번의 간단한 작업으로 배경색과 글자색을 바꿀 수 있었다
단, darkTheme과 lightTheme에서 색상 이름을 같게 해줬기 때문에 가능한 것이다
위에서 말했 듯, style component안에서 theme prop안 오브젝트의 이름을 읽고 있기 때문이다
이렇게 간단하게 theme에 대해서 정리해 보았다
이 글에서는 background-color와 color 두 개만을 이용했기 때문에 굳이..?라는 생각이 들 수 있으나,
사이트의 규모가 커진다면 매우 유용하게 사용할 수 있다 (a태그일 때, hover일 때, active일 때의 색 등등)
State Management인 Recoil을 블로그에서 다룬 후에, 다크모드를 구현하는 것도 포스팅 할 계획이다
더 자세한 내용은 공식문서에서 확인할 수 있다