[react] styled-components - Theming

sion·2022년 4월 30일
0

react

목록 보기
2/2

Styled Components Theming

Styled Components의 강점 중 하나는 테마를 제공하는 것이다.
컨텍스트 API를 통해 아래에 있는 모든 React구성 요소에 테마를 적용시킬 수 있다.

이를 활용하면 다크모드, 라이트모드 등 다양한 테마를 홈페이지에 적용시킬 수 있다.
(만약 CSS를 활용했다면..? 고생스러운 일이 아닐 수 없다.)

ThemeProvider

Styled Components에서는 ThemeProvider에 속한 모든 컴포넌트에게 theme속성을 가지게 해준다.
(Context API)

기본 사용방법은 다음과 같다.

// App.js
import styled, { ThemeProvider } from "styled-components";

const Wrapper = styled.section`
  background-color: ${props => props.theme.bgColor};
  color: ${props => props.theme.color};
  padding: 4em;
  text-align: center;
`;

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
`;
const theme = {
  bgColor: "black",
  color: "white"
}

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Wrapper>
        <Title>안녕하세요!</Title>
      </Wrapper>
    </ThemeProvider>
  );
}
export default App;

원하는 상위 컴포넌트에서 <ThemeProvider theme={사용자 정의}> theme props를 전달하여 하위 컴포넌트에서 받아 사용이 가능하다.

darkmode, lightmode

ThemeProvide를 사용하면 간단하게 darkmodelightmode를 사용할 수 있다.

//theme.js
export const dark = {
	bgColor: "black",
	color: "white"
}

export const light = {
	bgColor: "white",
	color: "dark"
}

// App.js

import styled, { ThemeProvider } from "styled-components";
import GlobalStyle from "./GlobalStyle";
import { useState } from "react";
import { dark, light } from "./theme";

const Wrapper = styled.section`
  background-color: ${props => props.theme.bgColor};
  color: ${props => props.theme.color};
  padding: 4em;
  text-align: center;
`;

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
`;

function App() {
  const [isDark, setIsDark] = useState(true);
  const handleMode = () => setIsDark(!isDark);
  const theme = isDark ? dark : light;
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle/>
      <Wrapper>
        <Title>안녕하세요!</Title>
      </Wrapper>
      <button onClick={handleMode}>모드변경</button>
    </ThemeProvider>
  );
}
export default App;

다음과 같은 방식으로 쉽게 다크모드 및 라이트모드를 구성할 수 있다.
추후 isDark 변수는 Redux와 같은 상태 관리 라이브러리로 제어할 수 있다.

GlobalStyle

만약 Theme을 활용하지 않고 모든 요소들에게 스타일을 적용시킬려면 어떻게 하면될까?
GlobalStyle을 활용하면 모든 요소들에게 스타일을 줄 수 있다.

// GlobalStyle.js
import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
  html, body, div, span, applet, object, iframe,
	h1, h2, h3, h4, h5, h6, p, blockquote, pre,
	a, abbr, acronym, address, big, cite, code,
	del, dfn, em, img, ins, kbd, q, s, samp,
	small, strike, strong, sub, sup, tt, var,
	b, u, i, center,
	dl, dt, dd, ol, ul, li,
	fieldset, form, label, legend,
	table, caption, tbody, tfoot, thead, tr, th, td,
	article, aside, canvas, details, embed,
	figure, figcaption, footer, header, hgroup,
	menu, nav, output, ruby, section, summary,
	time, mark, audio, video {
		margin: 0;
		padding: 0;
		border: 0;
		font-size: 100%;
		font: inherit;
		vertical-align: baseline;
	}
	/* HTML5 display-role reset for older browsers */
	article, aside, details, figcaption, figure,
	footer, header, hgroup, menu, nav, section {
		display: block;
	}
	body {
		line-height: 1;
	}
	ol, ul {
		list-style: none;
	}
	blockquote, q {
		quotes: none;
	}
	blockquote:before, blockquote:after,
	q:before, q:after {
		content: '';
		content: none;
	}
	table {
		border-collapse: collapse;
		border-spacing: 0;
	}
`;

export default GlobalStyle;

//App.js
function App() {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle/>
      <Wrapper>
        <Title>안녕하세요!</Title>
      </Wrapper>
    </ThemeProvider>
  );
}

GlobalStyle은 createGlobalStyle를 사용하여 생성하면 된다.
해당 내용은 css reset에 관한 내용으로 전체적인 요소에 적용할 스타일을 넣으면 된다.
또한 <GlobalStyle/>은 최상단에 위치시켜야 전체적인 요소에 적용시킬 수 있다.

참고

공식문서

profile
공부한 것을 글로 저장하자!

0개의 댓글