React

Styled-components(1) 스타일드 컴포넌트 설치하기

새발개발JA 2021. 10. 12. 14:19
반응형

지난 시간까지 코딩앙마 님의 강의를 듣고 타입스크립트로 포팅을 해보며 감을 익혔다.

이번 시간부터는 udemy 에서 프로젝트 실습을 시작하였다.  

평소부터 배우고 싶었던 styled-components 를 타입스크립트와 연동할 수 있도록 설치하는 과정을 기록해보았다.

 


Styled-components(1) 설치하기

 

- Styled-components 설치하기

$  npm install styled-components

터미널에 명령어를 입력하니 여러 디펜던시들이 설치되고 있다.

 

- Typescript(타입스크립트)와 함께 사용하기 위한 라이브러리 설치하기

$ npm install --save-dev @types/styled-components

터미널에 명령어를 입력하니 여러 디펜던시들이 설치되고 있다.

 

src/styles/global.ts

설치가 다 되었으니 테스트 코드를 짜보자.  흥미로운 점은 css 가 트리 구조로 짜여있다.

import { createGlobalStyle } from 'styled-components' 

export default createGlobalStyle`	// `` 를 꼭 컴포넌트 앞뒤로 붙여야 한다.
  html {
    height: 100%;

    body {
      display: flex;
      flex-direction: column;
      height: 100%;
      margin: 0;

      #root {
        background: ${theme.colors.background};
        color: ${theme.colors.black};
        display: flex;
        font-family: sans-serif;
        height: 100%;
        justify-content: center;
        padding: 15px;
      }
    }
`

 

src/styles/index.ts

GlobalStyles 라는 컴포넌트 이름으로 export 해주기

export { default as GlobalStyles } from './global'

 

src/index.tsx

최상단 화면에 <GlobalStyles> 라는 컴포넌트를 얹어주자.

import React from 'react'
import ReactDOM from 'react-dom'
import { unregister } from './core'
import { GlobalStyles } from './styles' // styled-component 파일을 임포트해오고

ReactDOM.render(
  <>					// fragment로 감싸주기
    <GlobalStyles /> 			// styled-component 파일을 추가하였다.
    <div>Hello World</div>
  </>,
  document.getElementById('root')
)

unregister()

 

 

 

 

반응형