Front-End/React(비공)
[React] styled components 3. theme darkmode 기초
리리히히
2024. 3. 20. 11:15
반응형
🔎 전체코드 한번에 보기
//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import styled, { 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>
);
//App.js
import styled from "styled-components"
const Title = styled.h1`
color: ${(props) => props.theme.textColor};
`
const Wrapper = styled.div`
display: flex;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
background-color: ${(props) => props.theme.backgroundColor};
`;
function App() {
return (
<Wrapper>
<Title>Hello</Title>
</Wrapper>
);
}
export default App;
🔎 코드 쪼개서 설명
import styled, { ThemeProvider } from 'styled-components';
- index.js 제일 상단 ThemeProvider 속성 추가
const darkTheme = {
textColor: "whitesmoke",
backgroundColor: "#111"
}
const lightTheme = {
textColor: "#111",
backgroundColor: "whitesmoke"
}
- darkTheme 및 lightTheme 컴포넌트 생성
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
</React.StrictMode>
);
- React.StrictMode 내부에 <App /> 컴포넌트를 ThemeProvider로 감싸준다.
const Title = styled.h1`
color: ${(props) => props.theme.textColor};
`
const Wrapper = styled.div`
display: flex;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
background-color: ${(props) => props.theme.backgroundColor};
`
- Title 컴포넌트의 h1의 텍스트 컬러 및 Wrapper 컴포넌트의 div의 배경컬러는 모두 props로 받아온다.
- dark/light mode 컴포넌트를 구성할 때 property 들의 이름은 똑같아야한다.
(textColor, backgroundColor...)
반응형