-
Styled-components로 테마모드 변경하기(다크모드·라이트모드)HTML·Style/Styled Components 2023. 6. 21. 02:39
여태 createGlobalStyle을 공통된 전역 스타일을 지정할때만 사용했다.
테마모드를 적용할 생각을 왜 못했지?

theme.ts
테마를 스타일링한다.
export const lightTheme = { bgColor: "#fff", textColor: "#222", accentColor: "#12cbef", }; export const darkTheme = { bgColor: "#282c35", textColor: "#fff", accentColor: "#ffe246", }; export const theme = { lightTheme, darkTheme, }; export default theme;Global.tsx
styled-reset을 추가 설치가 필요하다.
import { createGlobalStyle } from "styled-components"; import reset from "styled-reset"; export const GlobalStyle = createGlobalStyle` ${reset} body { background-color: ${({ theme }) => theme.bgColor}; color:${({ theme }) => theme.textColor}; margin: 0; padding: 0; list-style: none; box-sizing: border-box; } `;theme.bgColor와 theme.testColor 속성을 불러오지 못하는 오류가 발생해서, styled.d.ts파일을 추가로 작성했다.
> https://ddiddibbung.tistory.com/99
App.tsx
스타일이 필요한 컴포넌트에 isDarkMode를 내려준다.
모드를 변경할 toggle 버튼이 있는 곳에는 toggleDarkMode도 함께 내려준다.
import { useState } from "react"; import { Navigation } from "./components/Navigation"; import { Carousel } from "./components/Carousel"; import { MainProducts } from "./components/MainProducts"; import { Footer } from "./components/Footer"; import { ThemeProvider } from "styled-components"; import { darkTheme, lightTheme } from "./globalStyle/theme"; import { GlobalStyle } from "./globalStyle/GlobalStyle"; function App() { const [isDarkMode, setIsDarkMode] = useState<boolean>(true); const toggleDarkMode = () => { setIsDarkMode((prev) => !prev); }; return ( <> <ThemeProvider theme={isDarkMode ? darkTheme : lightTheme}> <GlobalStyle /> <Navigation isDarkMode={isDarkMode} toggleDarkMode={toggleDarkMode} /> <Carousel /> <MainProducts isDarkMode={isDarkMode} toggleDarkMode={toggleDarkMode} /> <Footer isDarkMode={isDarkMode} toggleDarkMode={toggleDarkMode} /> </ThemeProvider> </> ); } export default App;모드 변경에 따라 스타일링이 필요한 컴포턴트에 props를 내려준다.
<BrowserMode onClick={toggleDarkMode}> {isDarkMode ? "🌞" : "🚗"} </BrowserMode> <Search placeholder="Search" isDarkMode={isDarkMode}></Search>const Search = styled.input<{ isDarkMode: boolean }>` border-radius: 4px; background-color: ${(props) => (props.isDarkMode ? "#52545a" : "#d8dce7")}; border: 1px solid rgba(166, 173, 187, 0); color: ${(props) => (props.isDarkMode ? "#c0c1c7" : "#52545a")}; font-size: 16px; font-weight: 400; height: 48px; padding: 0 16px; margin: 0 16px; `props를 받아서 모드에 따라 자유롭게 스타일링하면 된다.
theme에 지정한 color를 사용하려면, background-color나 color 속성을 삭제해야 적용된다.
'HTML·Style > Styled Components' 카테고리의 다른 글
[styled-components] 다른 component에 접근해서 css를 바꿔보자! (0) 2023.02.07 [react]react-router-dom의 Link를 styled-components로 꾸미기 (0) 2023.01.25 [Styled Components] 전역 스타일(Global Style)과 기본 스타일(Default Theme) 관리 (0) 2022.12.21 [React] Styled Components 사용 방법 (0) 2022.12.15