일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- 백엔드
- Atomic Design 패턴으로 페이지 만들기
- Atomic Design
- git-hooks
- redis
- 배포
- 스타일 컴포넌트
- docker
- react
- 쿠버네티스
- GHCR
- 롱 폴링
- 배포자동화
- backend
- 예제
- aws
- yarn-berry
- 디렉토리이동
- Kubernetes
- styled-components
- Infra
- 도커
- 소켓IO
- 인프라
- 리액트
- 캐시
- 개발
- methodreference
- 자동화
- deployment
- Today
- Total
SLASH 기술 블로그
Styled Component 구현하기 본문
시작하기
Styled Component는 CSS-in-JS를 선호하는 나에게 있어 굉장히 좋은 라이브러리이다.
또한 누군가가 React 프로젝트에서 Style을 선언하는 방식에 대해 고민을 하고 있다면 Styled Component를 소개 해 줄 것이다.
이번 글에서는 Styled Component가 어떤 원리로 CSS-in-JS를 구현 할 수 있는지 간단하게 구현해보면서 이해해보자.
CSS-in-JS 핵심 문법
Styled-Components는 styled.{tagName}`` 이런식으로 선언하여 사용하게된다. 이때 ``안에다가 CSS코드를 작성하게 되는데 ``안에 있는 값을 파싱할 수 있게 해주는 것이 Tagged Template Literals 이다.
Tagged Template Literals 이란?
Tagged Template Literals를 알려면 Template Literals를 먼저 알아야 한다. Template Literals란 ECMAScript 2015에 나온 새로운 기능으로 백틱(``)을 사용하여 문자열을 표현하는 방법이다. 이것을 사용하면 기존에 + 연산자로 Stirng을 합쳐서 사용했던 방식에서 연산자를 사용 하지 않고 문자열을 합칠 수 있다.
const message = 'Hello World'
// ECMAScript 2015 이전
console.log('Welcome, ' + message + '!')
// ECMAScript 2015 이후
console.log(`Welcome, ${message}!`)
Tagged Template Literals는 Template Literals를 이용하여 함수의 인자를 파싱하여 넘겨주는 것이다. 아래의 예제 코드로 확인 해보자.
const firstValue = "World"
const secondValue = "!"
function taggedTemplate (string, first, second) {
console.log(string, first, second)
}
taggedTemplate`Hello, ${firstValue} ${secondValue} Good Day.`
이 코드의 콘솔 로그 결과를 보면 다음과 같다.
["Hello, ", " ", " Good Day."] "World" "!"
문자열은 첫번째 파라미터로 들어가고 나머지 변수 값들은 각각의 파라미터로 순서대로 들어가게 된다. 이 Tagged Template Literals를 활용하여 만든 라이브러리가 Styled-Components이다.
Styled-Components 만들어 보기
위에서 확인한 Tagged Template Literals를 활용하여 Styled-Components를 구현해보자.
먼저 Styled라는 함수는 컴포넌트를 반환 해주는데 tag 정보와 style 정보를 넘겨 받아서 처리해야한다.
우선 Styled Components를 사용하듯이 Button을 하나 만들어보자.
import React from 'react'
const Button = Styled('button')`
width: 60px;
height: 24px;
color: #222222;
border: 1px solid #222222;
border-radius: 4px;
cursor: pointer;
`
const Example = () => {
return <Button>하이</Button>
}
export default Example
이렇게 작성하면 Styled가 선언 되어 있지 않으니까 에러가 날 것이다.
이번 글의 핵심인 Styled를 추가해보자.
import React from 'react'
const Styled = HtmlTag => ([style]) => children => {
const ref = React.useRef()
React.useEffect(() => {
ref.current.setAttribute('style', style)
}, [])
return <HtmlTag ref={ref} {...children}/>
}
const Button = Styled('button')`
width: 60px;
height: 24px;
color: #222222;
border: 1px solid #222222;
border-radius: 4px;
cursor: pointer;
`
const Example = () => {
return <Button>하이</Button>
}
export default Example
코드를 보면 먼저 html tag 정보를 전달 해주고 Tagged Template Literals를 통해 style 정보를 넘겨 준 다음에 마지막으로 컴포넌트 안에 있는 Children 정보까지 전달하여 Component를 만들어서 return 해주면 끝난다.
하지만 위 코드를 보면 Styled-Components를 선언하는 방식과는 조금 다르다.
원래는 Styled.button이라고 해야하는데 우리가 만든 코드는 Styled('button')으로 되어있다.
defaultTags라는 리스트를 하나 만들고 Styled('button') 매핑 해주면 Styled.button으로 사용 할 수 있게 된다.
import React from 'react'
const defaultTags = [
'button'
]
const Styled = HtmlTag => ([style]) => children => {
const ref = React.useRef()
React.useEffect(() => {
ref.current.setAttribute('style', style)
}, [])
return <HtmlTag ref={ref} {...children}/>
}
defaultTags.forEach(tag => {
Styled[tag] = Styled(tag)
})
const Button = Styled.button`
width: 60px;
height: 24px;
color: #222222;
border: 1px solid #222222;
border-radius: 4px;
cursor: pointer;
`
const Example = () => {
return <Button>하이</Button>
}
export default Example
이렇게 하면 간단하게 Styled Component를 직접 만들어서 사용 할 수 있다.
이번 글에서는 간단하게 만들어봤기 때문에 Styled-Components내에서 props 정보를 다룰 수 없다.
또한 여러 보안 이슈 때문에 실제 프로젝트에서는 이런식으로 써서는 안된다. (Styled-Components를 설치해서 쓰도록 하자.)
이렇게 간단하게 Styled-Components를 직접 만들어 보았다.
어떤식으로 만드는지 궁금했던 분들에게 도움이 되었으면 좋겠다.
'styled-component' 카테고리의 다른 글
Styled Component로 다크모드 구성하기 (0) | 2021.04.23 |
---|---|
Styled Component 사용법 (0) | 2021.04.22 |
Styled Component란, 개인적인 생각 (1) | 2021.04.21 |