Main-Project[MAEIL MAIL] Refactoring

이창훈·2022년 10월 13일

maeilmail

목록 보기
1/2
post-thumbnail

다크모드 코드 수정

기존 코드


App.js

import { GlobalStyle } from './styles/GlobalStyle';
import { useSelector } from 'react-redux';
import { darkTheme, lightTheme } from './styles/theme';

function App() {
  const state = useSelector((state) => state.themeSlice);
  const themeObject = state.theme === 'light' ? lightTheme : darkTheme;

  return (
    <BrowserRouter>
      <GlobalStyle theme={themeObject} />
      <Router />
    </BrowserRouter>
  );
}

문제점
이렇게 할 경우 다크 모드인지 확인 하기 위해서 다크모드가 적용되는 모든 컴포넌트 마다

import { useSelector } from 'react-redux';
const themeState = useSelector((state) => state.themeSlice).theme;

를 해주고 html 태그들 마다 themeState={themeState}를 props로 내려주고

color: ${(props) => props.themeState === 'light' ? 'var(--color-black)' : '#D2D2D2'};

를 해줘야 했다.

수정한 코드

App.js

import { GlobalStyle } from './styles/GlobalStyle';
import { useSelector } from 'react-redux';
import { darkTheme, lightTheme } from './styles/theme';
import { ThemeProvider } from 'styled-components';

function App() {
  const state = useSelector((state) => state.themeSlice);
  const themeObject = state.theme === 'light' ? lightTheme : darkTheme;
  return (
    <ThemeProvider theme={state}>
      <BrowserRouter>
        <GlobalStyle theme={themeObject} />
        <Router />
      </BrowserRouter>
    </ThemeProvider>
  );
}

ThemeProvider 로 인해 모든 컴포넌트에서 styled.태그에 props로 내려주지 않아도 되며 아래의 코드들을 적을 필요 없이

import { useSelector } from 'react-redux';
const themeState = useSelector((state) => state.themeSlice).theme;

이렇게 해주면 된다.

color: ${(props) => props.theme.theme === 'light' ? 'var(--color-black)' : '#D2D2D2'};

props.theme.theme일 수 밖에 없는게

<ThemeProvider theme={state.theme}>

으로 라이트 모드인지 아닌지 string으로 보내주려고 했을 때는

Uncaught Error: ThemeProvider: Please make your "theme" prop an object.

라고 에러가 나왔다. ThemeProvider의 theme에는 반드시 객체가 주어져야한다.

profile
실패를 두려워하지 않고 배우고 기록하여 내일의 밑거름 삼아 다음 단계로 성장하겠습니다.

0개의 댓글