-
[React] styled-components 간단한 다크모드 만들기IT/React 2022. 6. 8. 00:39
간단한 기능이므로 부가적이 사항은 차후에 추가할 예정
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", } // 큰 회사라면 textColor, borderColor, lInkColor, HoverColor 등등 다양 root.render( <React.StrictMode> <ThemeProvider theme={lightTheme}> <App /> </ThemeProvider> </React.StrictMode> );- index.js 파일에서
- App 컴포넌트를 <ThemeProvider> 컴포넌트로 감싸준다.
- <ThemeProvider> 컴포넌트의 props로 theme={lightTheme} 를 작성해 준다.
- lightTheme, darkTheme는 본인의 자유
App
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>Hello</Title> </Wrapper> ); } export default App;- 주로 사용될 텍스트에
- color: $(props => props.theme.textColor
- 기본으로 사용될 background-color 에
- background-color: $(props => props.theme.backgroundColor) 로써
- 받은 props를 사용해준다
이렇게 작성하면 index.js 파일에서 light, dark 테마를 바꾸기만 하면 전체 테마가 바뀌는 모습을 볼 수 있다.
'IT > React' 카테고리의 다른 글
[React] CSS Gallery 의 React화 일지 - 4 (06.05 ~ 06.10) (0) 2022.06.10 [React] styled-components interface, optional props, Type State (typescripts) (0) 2022.06.09 [React] styled-components animation keyframes, & 선택자, $선택자, (0) 2022.06.07 [React] styled-components props, 상속, as, attrs (0) 2022.06.06 [React] CSS Gallery 의 React화 일지 - 3 (06.01 ~ 06.04) (0) 2022.06.04