[TIL] Style-component

2023. 9. 17. 16:37· 프론트엔드/React
목차
  1. 1. 기본 사용법 
  2. 2. prop
  3. 3. Extending Styles
  4. 4. animations
  5. 5.가상선택자(pseudo selectors)
  6. 6. ThemeProvider

공식문서 : https://styled-components.com/

vue styled-component: https://github.com/styled-components/vue-styled-components


 

1. 기본 사용법 

- 컴포넌트를 생성하는 동시에 스타일을 정의할 수 있음

import styled from "styled-components"

const Father = styled.div`
	display: flex;
	color: royalblue;
`

function App() {
  return(
   <Father> 
      <div>1</div>
      <div>2</div>
    </Father> 
    )
}

 

 

2. prop

: styled-component 템플릿 리터럴의 함수에서 props를 받을 수 있다.

import styled from "styled-components"

const Father = styled.div`
	display: flex; 
`

const Box = styled.div`
    width:100px;
    height: 100px;
    background-color: ${(prop)=>prop.bgColor};
`

function App() {
  return( 
     <Father> 
      <Box bgColor='tomato'  />
      <Circle bgColor='teal' /> 
    </Father>  
    )
}

 

 

3. Extending Styles

1) as : 태그만 바꾸기 

const Btn = styled.button`
    background-color: skyblue;
    width: 100px;
    height: 20px;
`

function App() {
  return( 
     <Father> 
       <Btn/>
       <Btn as="a"  /> 
     </Father> 
    )
}


2) Attrs : 속성을 갖는 스타일 컴포넌트 생성 가능

const InputEl = styled.input.attrs({required:true, maxLength:10})`
	background-color: skyblue;
`

function App() {
  return(
    <>       
       <InputEl/> 
    </>
    )
}

 

4. animations

- keyframes를 이용. 

- css의 @keyframes를 사용하지 않는이유
  : 컴포넌트에 스코핑 되지 않아, 글로벌로 선언되어 이름 충돌이 발생할 수 있기 때문이다.
  : 스타일드 컴포넌트로 만들면 랜덤한 class명을 생성해주기 때문에 클래스명이 중복되지 않게됨.

import styled,{keyframes} from "styled-components"

const rotateAni = keyframes`
    from{
      transform: rotate(0deg);
    }to{
      transform: rotate(360deg);
      background-color: teal;
    }
`


const RotateBox = styled.div`
    width: 100px;
    height:100px;
    background-color: tomato;
    display: flex;
    justify-content: center;
    align-items: center; 
    animation: ${rotateAni} 2s infinite ;
`

function App() {
  return(  
     <RotateBox>
     	 <span>🥰</span>
     </RotateBox>
    )
}

 

 

5.가상선택자(pseudo selectors)

1) 태그명을 selector로 사용하기

2) styled-component자체를 selector로 사용하기

const ContentBox = styled.p`
font-size:20px; 
`

const Wrapper = styled.div`
    width: 100px;
    height: 100px;
    background-color: beige;
    display: flex;
    justify-content: center;
    align-items: center;

/* 1) 태그명을 selector로 사용하기 */
      p{  
        &:hover{
        font-size:30px;
        } 
      }

/* 2) styled-component자체를 selector로 사용하기 */
      ${ContentBox}{  
        &:active{
          color: red;
        }
      }
` 

function App() {
  return( 
    <Wrapper>
      <ContentBox>내용</ContentBox>
    </Wrapper>  
  )
}

6. ThemeProvider

- 컨텍스트 API를 통해 ThemeProvider하위의 모든 컴포넌트에 테마를 제공함

- 하위 모든 컴포넌트에서 이 theme prop에 접근가능함

'프론트엔드 > React' 카테고리의 다른 글

Custom React 구현하기  (2) 2024.12.22
useState 의 setState는 비동적으로 동작  (0) 2024.05.06
useMemo, useCallback에 대해  (0) 2023.12.10
[TIL] React router6  (0) 2023.09.17
a태그와 router-link 차이(spa)  (0) 2023.06.30
  1. 1. 기본 사용법 
  2. 2. prop
  3. 3. Extending Styles
  4. 4. animations
  5. 5.가상선택자(pseudo selectors)
  6. 6. ThemeProvider
'프론트엔드/React' 카테고리의 다른 글
  • useState 의 setState는 비동적으로 동작
  • useMemo, useCallback에 대해
  • [TIL] React router6
  • a태그와 router-link 차이(spa)
journey-dev
journey-dev
journey-dev
journey-dev
journey-dev
전체
오늘
어제
  • 분류 전체보기 (63)
    • 프론트엔드 (44)
      • JS (8)
      • React (8)
      • vue (9)
      • Typescript (2)
    • CS (0)
      • 자료구조&알고리즘 (2)
      • 네트워크 (2)
    • 개발서적 (1)
      • 코어 자바스크립트 (0)
      • 프론트엔드 성능 최적화 가이드 (1)
    • DB (11)
      • SQL (11)
    • GIT (0)
    • GIS (3)
    • 개발일기 (0)
    • ing (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • 일단 시작해라. 나중에 완벽해지면 된다.

인기 글

태그

  • 리액트 복기하기!

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
journey-dev
[TIL] Style-component
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.