import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { ThemeProvider } from "styled-components";
const root = ReactDOM.createRoot(document.getElementById("root"));
const darkTheme = {
textColor: "whitesmoke",
backgroundColor: "#111",
};
const lightTheme = {
textColor: "#111",
backgroundColor: "#whitesmoke",
};
root.render(
<React.StrictMode>
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
</React.StrictMode>
);
ThemeProvider
를 "styled-components"
로 부터 import 하여 사용한다.
위 코드처럼 <App />
컴포넌트를 ThemeProvider
안에 있게 하고 theme
속성을 설정해준다.
이렇게 하면 ThemeProvider
안의 컴포넌트들이 theme 속성을 받아 쓸 수 있게된다.
이전 포스팅에서 사용한 예제에 덮어보면 아래와 같다.
import styled, { keyframes } from "styled-components";
const Parent = styled.div`
display: flex;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
background-color: ${(props) => props.theme.backgroundColor};
`;
const Rotation = keyframes`
0% {
transform: rotate(odeg);
border-radius: 0px
}
50%{
border-radius: 150px;
}
100% {
transform: rotate(360deg)
}`;
const Box = styled.div`
background-color: ${(props) => props.bgColor};
width: 300px;
height: 300px;
animation: ${Rotation} 1s linear infinite;
display: flex;
justify-content: center;
align-items: center;
h1 {
color: white;
&:hover {
color: black;
}
}
`;
function App() {
return (
<div>
<Parent>
<Box bgColor="tomato">
<h1>Loading...</h1>
</Box>
</Parent>
</div>
);
}
export default App;
코드가 예제가 길지만 봐야할 부분은 Parent
컴포넌트에 background-color
부분이다. 해당 코드에서 사용한것 처럼 theme 속성을 받아 사용할 수 있다.
다크모드와 라이트모드 객체를 별도로 생성하여 버튼 클릭시 변경해주는 방식으로 사용이 가능하다.
디자인 색상을 객체화시켜 사용함으로써 디자인 통일성을 얻게되며 수정작업이 빠르고 간편해진다.