본문 바로가기
내일배움캠프 TIL

2023-11-16 본 캠프 31일차 / 50일차 TIL

by KMS_99 2023. 11. 17.

2023-11-16 본 캠프 31일차 / 50일차 TIL

주요 진행사항

- 알고리즘 문제풀이

- 리액트 강의 수강

- 챌린지반 수업

 

챌린지반 수업 - styled componenet <ThemeProvider>

 

(1) ThemeProvider 모듈이란?

styled-components 모듈에서 사용할 수 있는 컴포넌트 중 하나로,

ThemeProvider 컴포넌트 내부에 선언된 컴포넌트는 theme라는 속성 내에 객체 형태로 선언된 스타일들을 모두 사용 가능하게 해준다.

이런 방식으로 여러 theme를 부여해 줄 수 있다.

 

(2) ThemeProvider 사용법

 

- styled-components 설치

npm install styled-components

yarn add styled-components

 

- theme.js 파일 생성

//theme.js

// 테마 추가
const lightTheme = {
	background : 'white',
    color : 'black',
}

const darkTheme = {
	background : 'black',
    color : 'white'
}


// 테마 정보가 들어있는 객체 export
export const themes = {
	white:lightTheme,
    dark : darkTheme,
}

 

- ThemeProvider로 theme를 사용할 컴포넌트 감싸기

import React, {useState} from 'react';
import {ThemeProvider} from 'styled-components';
import Header from './Header';
import Main from './Main';
import Footer from './Footer';
import {themes} from './theme';

const App = () => {
	const [currentTheme, setCurrentTheme] = useState('light');
	return(
    	<ThemeProvider theme={themes[currentTheme]}>
            <Header setCurrentTheme={setCurrentTheme}/>
            <Main />
            <Footer />
        </ThemeProvider>
    )
};

export default App;

 

- styled components에 theme 스타일 적용

// Header.js

import React from 'react';
import {styled} from 'styled-components';

const Header = ({setCurrentTheme}) => {
	const changeThemeHandler = () => setCurrentTheme(prev=>prev==='light'?'dark':'light');
    
	return (
    	<StDiv>
        	<h1>테스트</h1>
            <button onClick={changeThemeHandler}>themeChangeBtn</button>
        </StDiv>
    )
};

const StDiv = styled.div`
	background: ${props=>props.theme.background}
    color: ${props=>props.theme.color}
`;

export default Header;