새로고침 시에도 선택한 테마를 유지하기 위해 테마 상태를 로컬스토리지에 저장하고 state의 기본값을 로컬스토리지에 저장된 테마 상태를 불러온다.
타입스크립트에서 구현 시 styled.d.ts
파일에 스타일들의 타입을 지정해 주어야 한다.
// theme.tsx
import { DefaultTheme } from "styled-components";
export const lightMode: DefaultTheme = {
logo: `#22262c`,
background: `white`,
mainText: `#22262c`,
subText: `#495057`,
mainColor: `#ffefd5`,
diaryBackground: `white`,
diaryDate: `#9aa1a8`,
diaryInfoLine: `#f1f3f5`,
TagColor: `#22262c`,
disabledTagColor: `gray`,
disabledTagBorder: `#d1d1d1`,
disabledTagBackground: `white`,
buttonHover: `#ffdeb7`,
disabled: `lightgray`,
};
export const darkMode: DefaultTheme = {
logo: `#ececec`,
background: `#1f2125`,
mainText: `#ececec`,
subText: `#a6a6a6`,
mainColor: `#ffefd5`,
diaryBackground: `#2f3135`,
diaryDate: `#9aa1a8`,
diaryInfoLine: `#3C4048`,
TagColor: `#22262c`,
disabledTagColor: `gray`,
disabledTagBorder: `none`,
disabledTagBackground: `#2f3135`,
buttonHover: `#ffdeb7`,
disabled: `gray`,
};
// styled.d.ts
import "styled-components";
declare module "styled-components" {
export interface DefaultTheme {
logo: string;
background: string;
mainText: string;
subText: string;
mainColor: string;
diaryBackground: string;
diaryDate: string;
diaryInfoLine: string;
TagColor: string;
disabledTagColor: string;
disabledTagBorder: string;
disabledTagBackground: string;
buttonHover: string;
disabled: string;
}
}
// App.tsx
import { useState } from "react";
import { Routes, Route } from "react-router-dom";
import { createGlobalStyle, ThemeProvider } from "styled-components";
import { lightMode, darkMode } from "./theme";
function App() {
const LocalTheme = window.localStorage.getItem("theme");
const [isChange, setIsChange] = useState(LocalTheme);
const changeMode = () => {
const changeTheme = isChange === "light" ? "dark" : "light";
setIsChange(changeTheme);
localStorage.setItem("theme", changeTheme);
};
return (
<ThemeProvider theme={isChange === "dark" ? darkMode : lightMode}>
<div className='App'>
<GlobalStyle />
<LoginHeader isChange={isChange} changeMode={changeMode} />
<Routes>
<Route path='/' element={<Main />} />
<Route path='/NewDiary' element={<NewDiary />} />
<Route path='/Mypage' element={<Mypage />} />
<Route path='/Login' element={<Login />} />
<Route path='/Signup' element={<Signup />} />
<Route path='/DetailDiary/:diaryId' element={<DetailDiary />} />
<Route path='/EditDiary/:diaryId' element={<EditDiary />} />
</Routes>
</div>
</ThemeProvider>
);
}
export default App;