🔎 전체코드 한번에 보기
//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...)
반응형
'Front-End > React(비공)' 카테고리의 다른 글
[React] TypeScript2 (0) | 2024.03.21 |
---|---|
[React] TypeScript (0) | 2024.03.20 |
[React] styled components 2. animation, selector (0) | 2024.03.20 |
[React] styled components 1 (0) | 2024.03.19 |
[React] 리액트 프로젝트 설치, 세팅 (0) | 2024.03.19 |