[React] theme 적용법

bongkey·2022년 11월 26일
0

React

목록 보기
5/6

1. ThemeProvider 생성

ThemeProvider를 생성하고
theme object를 속성에 넣어주고 (우선 darkTheme 적용) App을 감싸준다.

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { ThemeProvider } from 'styled-components';
import App from './App';

const darkTheme = {
  color: 'whitesmoke',
  backgroundColor: '#111111',
};

const lightTheme = {
  color: '#111111',
  backgroundColor: 'whitesmoke',
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>,
);

2. theme 적용

theme object에 있는 값들을 활용하여 스타일링에 활용한다.

App.js

import styled from 'styled-components';

const Container = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  background-color: ${(props) => props.theme.backgroundColor};
`;

const Title = styled.h1`
  color: ${(props) => props.theme.color};
`;

function App() {
  return (
    <Container>
      <Title>Hello</Title>
    </Container>
  );
}

export default App;

적용 화면

각 theme는 1의 ThemeProvider에
넣는 theme object를 바꿔주어 적용 가능하다.

dark

light

출처

📝 nomadcoder react master class

profile
꾸준하게 기록하는 습관을 가지자

0개의 댓글