2023. 3. 28. 11:13ㆍ개발/react,next
리액트에서 여러 페이지마다 태마 색상을 지정하는 방법은 다양합니다. 여기에는 두 가지 일반적인 방법이 있습니다.
- Context API를 사용하여 전역 테마 상태 관리
Context API를 사용하여 전역적으로 테마 색상을 관리할 수 있습니다. 이를 위해서는 테마 상태와 해당 테마 상태를 변경하는 함수를 제공하는 ThemeProvider를 만들어야합니다. 예를 들어, 다음과 같은 코드를 사용할 수 있습니다.
import React, { createContext, useState } from 'react';
export const ThemeContext = createContext({
theme: 'light',
setTheme: () => {},
});
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export default ThemeProvider;
위 코드에서 ThemeContext는 전역 테마 정보를 관리하는 컨텍스트입니다. ThemeProvider는 ThemeContext.Provider를 래핑하고, theme 상태와 toggleTheme 함수를 제공합니다. toggleTheme 함수를 사용하면 theme 상태를 변경할 수 있습니다.
ThemeProvider 컴포넌트를 사용하려면, 먼저 애플리케이션 최상위에 위치시켜야합니다. 예를 들어, 다음과 같이 사용할 수 있습니다.
import React from 'react';
import ReactDOM from 'react-dom';
import ThemeProvider from './ThemeProvider';
ReactDOM.render(
<ThemeProvider>
<App />
</ThemeProvider>,
document.getElementById('root')
);
그리고 태마를 사용하는 모든 컴포넌트에서 ThemeContext를 사용하여 테마 상태를 가져와 사용할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';
const HomePage = () => {
const { theme } = useContext(ThemeContext);
return (
<div className={`home-page ${theme}`}>
<h1>Home Page</h1>
</div>
);
};
export default HomePage;
위 코드에서 HomePage 컴포넌트는 ThemeContext를 사용하여 현재 테마를 가져와 사용합니다. 이렇게 하면 각 페이지에서 다른 테마 색상을 사용할 수 있습니다.
- CSS Custom Properties를 사용하여 지역적으로 테마 색상 관리
CSS Custom Properties를 사용하여 지역적으로 테마 색상을 관리할 수도 있습니다. 이를 위해서는 각 페이지마다 다른 테마 색상을 정의하고 해당 페이지의 CSS 파일에서 사용할 수 있도록 해야합니다. 예를 들어, 다음과 같은 코드를사용하여 두 가지 다른 테마 색상을 정의할 수 있습니다
:root {
--primary-color: #0077FF;
--secondary-color: #FF4D4F;
}
.dark-theme {
--primary-color: #D4D4D4;
--secondary-color: #FFBABA;
}
위 코드에서 :root는 전역 CSS 변수를 정의하는 데 사용되며, --primary-color와 --secondary-color는 각각 기본 및 보조 색상을 정의합니다. dark-theme 클래스는 어두운 테마의 색상을 재정의합니다.
그런 다음 각 페이지의 CSS 파일에서 이러한 변수를 사용할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.
.page {
background-color: var(--primary-color);
color: var(--secondary-color);
}
위 코드에서 --primary-color와 --secondary-color 변수를 사용하여 페이지의 배경색과 글꼴 색상을 설정합니다. 이러한 방식으로 각 페이지에서 다른 테마 색상을 사용할 수 있습니다.
하지만 이 방법은 전체 앱에서 일관된 테마를 유지하기 어려울 수 있습니다. 따라서 전역 상태 관리와 CSS Custom Properties를 함께 사용하여 더 일관된 테마를 관리할 수도 있습니다.
'개발 > react,next' 카테고리의 다른 글
리액트 CRUD 기본 코드 useState([]) (0) | 2023.03.30 |
---|---|
Redux (0) | 2023.03.29 |
AI가 정리해준 리액트 (0) | 2023.03.28 |
"useRoutes() may be used only in the context of a <Router> component." (0) | 2023.03.24 |
export 'Switch' (imported as 'Switch') was not found in 'react-router-dom' (0) | 2023.03.23 |