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에는 반드시 객체가 주어져야한다.