SLASH 기술 블로그

Styled Component 사용법 본문

styled-component

Styled Component 사용법

SLASH 2021. 4. 22. 23:53
반응형

styled-component란 + 개인적인 생각이라는 글에서 나는 styled-component가 react에서 스타일을 다룰 때 좋은 것 같다고 했다. 이번 글에서는 나는 어떻게 코드를 작성하는지 보여주려고 한다.

 

styled-component 사용법

보통 여러 styled-component 예제들은 상태의 따른 스타일 변경을 Props를 통해 아래와 같이 작성 할 것이다.

 

예제1.

import React from 'react'
import styled from 'styled-components'

const Box = styled.div`
  ${(props) => props.hide && `display: none;`}
`

const Example1 = () => {
  const [hide, setHide] = React.useState(false)
    
  return <Box hide={hide} onClick={() => setHide(true)}/>
}

export default Example1

이 예제는 hide 상태 값의 따라 Box를 숨기는 코드이다. 대부분의 코드들은 이렇게 설명하고 있고 이것이 일반적이다. 하지만 나는 아래와 같은 형태로 작성한다.

 

예제2.

import React from 'react'
import styled from 'styled-components'

const Box = styled.div`
  &.hide {
    display: none;
  }
`

const Example1 = () => {
  const [hide, setHide] = React.useState(false)
    
  return <Box className={hide && 'hide'} onClick={() => setHide(true)}/>
}

export default Example1

이 예제는 props로 Box의 상태를 변경하는 것이 아닌 className으로 상태를 변경한 코드이다. 개인적으로 자신이 작성한 코드에는 이유가 존재 해야한다고 생각한다. styled-component를 꾸준히 사용해오면서 다음과 같은 나만의 규칙이 생겼다.

 

- Props로 상태를 바꾸는 경우

    1. 해당 Dom이 Props에 따라 완전히 다른 형태가 되려고 할 때

    2. Depth가 깊지 않거나 단일 Dom일 때

- ClassName으로 바꾸는 경우

    1. 형태 자체가 바뀌는 것이 아닌 특정 기능을 추가로 하려고 할 때

    2. Depth가 깊은 구조에서 자식 Dom이 부모의 상태값의 따라 바뀌어야 할 때

 

두가지의 사용 방법과 내가 어떤식으로 두가지의 방법을 나눠서 쓰는지 알았으니 아래에서 실제 코드를 통해 좀 더 자세한 예제로 확인해보자.

 

의미적으로 styled-component 다르게 사용해보기

위에서 나는 Props로 상태를 바꿀때와 ClassName으로 상태를 바꿀때를 내가 정한 상황의 맞게 나눠서 사용한다고 했다.

예제를 통해 어떤 상황일때 어떻게 쓰는지 구체적으로 확인 해보자.

 

예제1. (Props로 바꾸는 경우)

import React from 'react'
import styled from 'styled-components'

const primaryStyle = css`
  width: 24px;
  height: 24px;
  background: blue;
`

const typeStyle = {
  primary: primaryStyle,
  //...other types
}

const Button = styled.button`
  ${({ type }) => typeStyle[type]};
`

const Example1 = () => {
  return <Button type={'primary'}/>
}

export default Example1

이게 내가 말했던 Props로 바꾸는 상황이다. 버튼이라는 구성요소가 type에 따라 테두리가 생기거나 크기가 달라지거나 여러가지 스타일이 완전히 바뀔때에는 이렇게 하는게 보기 명확해진다. 그리고 Button은 최소 단위이기 때문에 버튼의 형태를 바꾸는 type요소로 인하여 추가적으로 변경되는 부분이 없다.

 

근데 만약 아래의 예제처럼 된다면 어떻게 될까?

 

예제2. (ClassName으로 바꾸는 경우)

import React from 'react'
import styled from 'styled-components'

const Card1 = styled.div`
 //...styles
`
const Section1 = styled.div`
 //...styles
 .special_event_on & {
   background: black;
 }
`
const Section2 = styled.div`
 //...styles
 .special_event_on & {
   background: blue;
 }
`
const Section3 = styled.div`
 //...styles
 .special_event_on & {
   background: red;
 }
`

const Example1 = () => {
  const [event, setEvent] = React.useState(false)
  
  return (
    <Card1 className={event && 'special_event_on'} onClick={() => setEvent(true)}>
      <Section1/>
      
      <Section2>
        <Section3>
        
        </Section3>
      </Section2>
    </Card1>
  )
}

export default Example1

Card1의 상태의 따라 자식 Components의 모든 상태가 바뀌는 상황이다. 만약 이것 또한 Props로 처리 하려고 하면 Section1, Section2, Section3에도 event props를 넘겨줘야한다. 하지만 ClassName으로 처리하게 되면 최상위 Dom의 ClassName만 추가하면서 Class 유무를 통해 모든 요소의 상태를 변경 할 수 있다.

 

나는 나만의 방식으로 여러 상황들을 적절하게 판단하여 styled-component를 사용하고 있다.

이렇게 나누는 방법은 정답이 아니며 많은 사람들이 다들 자신만의 기준과 규칙을 통해 개발을 하고 있을 것이라 믿는다. 모두 자신만의 이유나 생각이 들어간 코드를 작성 했으면 좋겠다.

 

@JJoGeon

반응형

'styled-component' 카테고리의 다른 글

Styled Component 구현하기  (0) 2021.04.25
Styled Component로 다크모드 구성하기  (0) 2021.04.23
Styled Component란, 개인적인 생각  (1) 2021.04.21
Comments