[React] 협업을 위한 공통 색 변수 저장하기 theme.js

2022. 9. 16. 00:59Study/React

    CSS에서 색상값을 변수로 지정하여 사용해보았다. 티웨이 홈페이지를 리액트로 클론하는 프로젝트를 진행하며, 색상값을 공통적으로 사용할 수 있으면 좋을 것 같아 알아보게 되었다.

     

    CSS에서 색상값을 변수로 사용하는 법

    :root {
    	--main-bg-color : brown;
    }

    이후에

    .one {
    	background-color: var(--main-bg-color);
    }

    와 같이 사용할 수 있었다. 반복 코드를 줄일 수 있고 가독성을 높일 수 있다. 

     

    리액트에서 색상값을 변수로 사용하는 법

    theme와 createGlobalStyle을 사용하는 법이 있다. 그 중에서 theme를 이용해보도록 하겠다.

    사용할 변수들을 다음과 같이 저장한다. 따로 파일로 저장하지 않고 같은 파일 내에 변수로 선언해줘도 괜찮다.

     

    Theme.js

    /* 색상 혹은 색상 팔레트를 이용한 글로벌한 정의가 필요한 스타일이 있을 때 사용합니다
    
    ** 사용법
        - ThemeProvider를 import 합니다
        - 모든 컴포넌트를 ThemeProvider에 연결해야 합니다
        - 컴포넌트에 props로 글로벌 정의한 스타일을 가져옵니다
    */
    const theme = {
        red: "#D22C26",
        green: "#82AB42",
        white: "#FFFFFF",
        tan: "#D8D3C4",
        beige: "#F4ECCF",
        dimgray: "#7D756D",
        softgreen: "#E4EEC0",
        softblue: "#D6E4F2"
    };
    
    export default theme;

    사용하려는 컴포넌트에서 ThemeProvider를 import한다. theme.js 파일로 만들었을 경우에는 파일도 import한다. 상위에 위치 시키고 적용하려는 theme를 props로 보내준다.

     

    AffIcon.js

    import React from "react";
    import styled from "styled-components";
    import { ThemeProvider } from "styled-components";
    import theme from "data/theme";
    .
    .
    .
    
    export default function AfflIcon(props) {
      return (
        <>
        {/*상위에 위치시키고 theme를 props로 보내줍니다*/}
          <ThemeProvider theme={theme}>
          <h1>제휴서비스</h1>
            <TopWrapper>
              <Button />
            </TopWrapper>
            .
            .
            .
        </>
      );
    }

    이하의 컴포넌트에서 props.theme로 불러 다음과 같이 사용할 수 있다.

    Button.js

    const StyledCircle = styled.button`
     .
     .
     .
      :hover {
        background: ${(props) => props.theme.red};
      }
    `;

     

    참고 자료 :

    https://developer.mozilla.org/ko/docs/Web/CSS/Using_CSS_custom_properties

    https://itchallenger.tistory.com/592

     

    리액트 개발자를 위한 CSS Variable

    원문 : https://www.joshwcomeau.com/css/css-variables-for-react-devs/ CSS Variables for React Devs CSS Variables are *really* cool, and they're incredibly powerful when it comes to React! This tutori..

    itchallenger.tistory.com

    맨 위로
    // //