Styled component의 theme 활용 팁

hyeok·2022년 4월 3일
0
post-thumbnail

styled component의 theme provider 기능을 활용하면 특정 variable에 css값을 할당해놓고 추후에 변경사항이 있으면 프로젝트 내부에서 일괄적으로 변경 가능하다.

import { ThemeProvider } from 'styled-components';
import {Button} from "antd"

const theme = {
  mainColor: "mediumseagreen"
};

render(
  <div>
    <Button>Normal</Button>

    <ThemeProvider theme={theme}>
      <StyledButton>Theme</StyledButton>
    </ThemeProvider>
  </div>
);

const StyledButton = Styled(Button)(({theme})=>{
	return{
    	["&&"]:{
    		background: theme.mainColor
        }
    }
})

기존에 nextjs 세팅하기에서도 설명했었다. 위의 mainColor만 바꾸면 유용하게 색깔을 바꿀수있다.

여기에서 3가지 팁을 공유하겠다.
첫째로는 antd의 설정된 css를 오버라이딩하는 방법이다. "&"를 이용해서 class를 추가해서 css 적용 우선순위를 높이는 방법이다. 예를들어 버튼의 기본 background색깔이 있다면 이를 이기고 내가 원하는 생깔로 커스터마이징하려면 !important를 써야하는데 이것보다는 Class를 '&'를 이용해서 추가해서 css적용 우선순위를 높이는게 낫다.

둘째로는 일반적으로 리터럴보단 functional한 styled component를 활용이다. 지금 회사에선 theme활용을 더 간편하게 하기위해서 functional로 styled component를 활용하고 있다.

const Button = styled.button`
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;

  /* Color the border and text with theme.main */
  color: ${props => props.theme.main};
  border: 2px solid ${props => props.theme.main};
`;

위의 예는 리터럴로 정의한 Button이다.

const Button = styled.button(({theme})=>{
    return { 
    fontSize: 1em,
    margin: 1em,
    padding: "0.25em 1em",
    borderRadius: 3, 

    /* Color the border and text with theme.main */
    color: theme.main,
    border: `2px solid ${theme.main}`
    }
  }
`;

위의 예가 functional 로 정의된 버튼이다. 기존 props로 따로 받는 부분이 없어서 좀 더 간단하게 theme를 활용할 수 있다.

셋째로는 theme를 useTheme를 활용해서 컴포넌트 함수 내부에서도 활용하는 것이다.
에를 들어 css property를 프롭스로 내려야하는데 이때 theme내부의 값을 활용하고싶다?

import { useTheme } from 'styled-components'

const theme = useTheme()

<CustomButton color={theme.primaryColor}>

이렇게 활용하면 된다. 이 부분은 styedcomponent 심화(https://styled-components.com/docs/advanced)에 나와있다.

profile
내가 만든 소프트웨어가 사람들을 즐겁게 할 수 있기 바라는 개발자

0개의 댓글