-
[styled-component] ThemeProvider로 다크모드 구현해보기!Front-end/React 2022. 4. 13. 19:08
안녕하세요! 오늘은 styled-components의 ThemeProvider를 통해 간단하게 다크모드를 구현해보도록 하겠습니다! 중간에 recoil이 잠깐 등장하는데! recoil이 궁금하신 분은! 🧐
https://sangjuntech.tistory.com/27
[상태관리, Recoil] Recoil을 사용해보자!
안녕하세요! 오늘은 상태관리를 위한 패키지 중 하나인 "Recoil"에 대해 알아보도록 하겠습니다! 상태관리를 위한 패키지 중에는 많은 것들이 있는데요. 대표적으로 "Redux"가 있죠! 👏🏻 저는 개
sangjuntech.tistory.com
여기에서 recoil에 대해 알아보면 좋을 것 같습니다 ㅎㅎ 👀 자 그럼 같이 ThemeProvider를 알아볼까요!
우선 ThemeProvider은 styled-components의 재미있는 magic중 하나입니다! 우리가 전역적인 style-theme을 구현할 때 정말 정말 정마아알 좋은 기능이죠! theme하면 다크모드와 나이트모드 아니겠습니까 🌞 🌔
이 ThemeProvider를 통해 다크모드와 나이트모드를 recoil과 함께 구현해보도록 합시다!
ThemeProvider?
themeProvider은 context API와 유사한 작동방식을 가지고 있습니다! 이 것을 래핑해주면, 우리는 전역적으로 theme의 스타일을 사용할 수 있게 되죠! 🌞
제 프로젝트에서 예시 코드를 가져와 보도록 하겠습니다!
const darkTheme = { color: 'white', bgColor: 'rgb(50,50,50)', containerColor: 'rgb(30,30,30)', textAlign: 'flex-end', }; const lightTheme = { color: 'black', containerColor: 'rgb(220,220,220)', textAlign: 'flex-start', bgColor: 'white', }; function App() { const darkmode = useRecoilValue(darkMode); return ( <ThemeProvider theme={darkmode ? darkTheme : lightTheme}> <Globalstyled /> <TodoList /> </ThemeProvider> ); } export default App;
recoil을 토이 프로젝트에서 ThemeProvider을 래핑해준 모습입니다. 그리고 우리는 darkTheme이라는 객체와 lightTheme이라는 객체를 가지고 있죠! recoil을 통해 darkmode가 true이면 darktheme을 적용하고, false라면 lightTheme을 적용시켜주도록 합니다!
이제 src/common에 폰트에서 어떻게 적용을 하는지 예시로 확인해 보도록 하겠습니다!
import styled from 'styled-components'; interface IFont { fontSize: string; fontWeight: string; fontColor?: string; marginRight?: string; marginBottom?: string; marginTop?: string; } export const Font = styled.p<IFont>` font-size: ${(props) => props.fontSize}; font-weight: ${(props) => props.fontWeight}; color: ${(props) => props.theme.color}; margin-right: ${(props) => props.marginRight}; margin-bottom: ${(props) => props.marginBottom}; margin-top: ${(props) => props.marginTop}; `;
물론 훨씬 좋은 방법이 있겠지만, 저는 전역적으로 사용하는 font같은 경우 color를 ThemeProvider에서 가져와서 사용을 했습니다. 우리가 아까 ThemeProvider를 전역에서 사용 가능하게 래핑을 해줬기 때문에 우리는 어떠한 depth를 거치지 않고도 theme객체를 가져올 수 있게 되는 것이죠!
자 그럼 Flow를 다시 확인해봅시다!
Work Flow
Recoil darkMode state에서 true, false 상태관리 => 상태에 따라 theme 인자가 darkMode인지 lightMode인지를 구분, => theme을 전역으로 가져올 수 있음 => 정의해둔 darkMode, lightMode theme을 사용하여 스타일링
이렇게 background color, font color등을 우리가 설정한 어떠한 테마에 맞게 사용할 수 있습니다! 그리고 그 darkmode를 recoil로 관리해주면! 우리는 어떠한 props를 받지 않고 다크모드를 구현할 수 있게 됩니다! 짝짝짝
오늘은 이렇게 간단하게 ThemeProvider를 알아보았습니다!
다른 좋은 방법도 많지만, styled-components를 사랑하는 저에게 정말 좋은 마법같은 기능이라 소개해드리고 싶었습니다 ㅎㅎ! 오늘도 글 읽어주셔서 감사합니다. 도움이 되셨다면 좋겠습니다!!
'Front-end > React' 카테고리의 다른 글
[React-query] 리액트 쿼리를 사용해보자! (0) 2022.03.29 [Typescript,React] Typescript로 Form,UseState 사용해보기 (2) 2021.12.14 [Styled-component] styled-component 좀 더 똑똑하게 쓰기 (3) 2021.12.13 [React] 리액트 꿀라이브러리 탐방 (1) 2021.12.08