theme을 사용해서 darkmode와 lightmode를 적용해보겠습니다.
theme이란? 여러가지 색상들을 가지고 있는 object입니다.
- theme 실행 방법
1) ThemeProvider import 하기

2) 환경셋팅 -> index.js
- App을 ThmemProvider로 둘러싸기
- theme object 생성하기 -> dark/lignt mode를 가지는 두개의 theme은 property가 똑같아야 합니다.
- object를 ThemeProvider에 전달하기 -> ThemeProvider 안에 있는 모든 컴포넌트들은 이 object에 접근할 수 있게됩니다.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { ThemeProvider } from 'styled-components';
const darkTheme = {
textColor : "whitesmoke",
backgroundColor: "#111",
};
const lightTheme = {
textColor : "#111",
backgroundColor: "whitesmoke",
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
</React.StrictMode>
);
3) theme 사용하기 -> app.js
props를 통해서 theme의 색상에 접근할 수 있습니다.
import styled from "styled-components";
const Wrapper = styled.div`
display: flex;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
background-color: ${(props)=> props.theme.backgroundColor};
`
const Title = styled.h1`
color: ${(props) => props.theme.textColor};
`
function App() {
return (
<Wrapper >
<Title>Title</Title>
</Wrapper>
)
}
export default App;
- darktheme 적용된 결과

지금은 darkmode와 lightmode를 설정할 때 ThemeProvider에 전달되는 theme={darkTheme} 혹은 theme={lightTheme}으로 변경해야하지만 다음에는 theme을 바꾸는 좋은 방법을 알아보겠습니다.
다음 포스팅부터는 typescript를 이용해서 theme 설정에 어떻게 도움 줄 수 있는지 배워보도록 하겠습니다!
'프론트엔드 > ReactJS 마스터' 카테고리의 다른 글
| [React] Typescript - interface로 props type 알려주기 (0) | 2023.05.11 |
|---|---|
| [React] React에서 Typescript 사용하기 - 환경셋팅 (1) | 2023.05.10 |
| [React] styled component(4) - Animations and Pseudo Selectors/State Selectors (0) | 2023.05.10 |
| [React] styled component(3) - As and Attrs (0) | 2023.05.09 |
| [React] styled components(2) - props로 컴포넌트 설정 변경하기, 컴포넌트 확장하기 (0) | 2023.05.02 |