[TIL 59] styled-components props로 theme color 내려주기

sunny·2021년 7월 14일
0
post-thumbnail

일반적으로 styled-component에서 theme.js에 설정한 속성값들을 사용할땐 이런식으로 사용한다.

<Container></Container>

...

const Container = styled.div`
  ${flexSet('flex-start', 'center')};
  background-color: ${({ theme }) => theme.themeColor};
`;

그런데, 이렇게 컴포넌트 내에서 props에 값에 따라 바뀌게 하려면 어떻게 해야할까?

<Title color={...}>

물론, 이런식으로 작성할 수도 있다.

<Title color="blue" />

...

const Title = styled.span`
  ${({ color, theme }) => {
    if (color === 'blue') {
      return css`
        color: ${theme.blue};
      `;
    }
  }}
`;

그렇지만 theme에 작성한 것들을 바로 활용하고 싶을때! 어떻게 해야할지 알아보자.


우선, styled-components에서 theme을 컴포넌트로 내려줄때 ThemeProvider를 사용한다. ThemeProvider는 context 를 사용해서 모든 리액트 컴포넌트에게 theme 속성을 전달하는 역할을 한다.

ThemeProvider로 theme 속성을 내려준다는 것을 이용해 component에서 바로 theme속성을 사용해보자!


useContext

useContext는 context 객체를 받아 context의 현재 값을 반환한다. context의 현재 값은 Hook을 호출하는 컴포넌트에 가장 가까이에 있는 <MyContext.Provider>의 value prop에 의해 결정된다.

useContext의 특성을 이용해 theme을 가져와서 사용할 수 있다.

import React, { useContext } from 'react';
...
const themeContext = useContext(ThemeContext);

themeContext를 console에 찍어보면 내가 지정한 theme속성들이 출력된다.


<Title color={themeContext['blue']}></Title>
<Title color={themeContext['orange']}></Title>

이렇게 key값을 이용해 지정한 속성들을 사용할 수 있게 된다.

profile
blog 👉🏻 https://kimnamsun.github.io/

0개의 댓글