본문 바로가기
front-end/CSS

[React-css] styled-component 설치 및 사용법 + 작업환경 셋팅하기

by -제이리 2022. 4. 5.
728x90
320x100

CSS-in-JS

스타일 정의를 CSS 파일이 아닌 JavaScript로 작성된 컴포넌트에 바로 삽입하는 스타일 기법.

Component가 많을 경우, class명이 중복될 수 있는 문제를 방지해준다.


 

💅 1. 패키지 설치

(1) 터미널로 설치.

$ npm i styled-components

//타입스크립트로 작성시 아래와 같이 입력
$ npm i styled-components @types/styled-components

 

 

(2) component파일 상단에 styled함수를 임포트한다.

import styled from "styled-components";

💅 2.  사용방법

(1) 기본문법 styled.태그 뒤에 백틱(``)을 작성하고 그안에 css스타일링을 한다.

(작명시 첫글자 대문자 필수)

const 태그작명 = styled.div` 
   padding: 20px;
   background-color: red;
`

(2) 응용

 

  • 조건부 & 가변 스타일링
const StyledDiv = styled.div`
	width: 100px;
    	height: 50px;
    color: ${(props)=>
    	props.color === "white" ? white : black
    }
`

return <StyledDiv></StyledDiv>

 

 

  • 확장 스타일링 : 기본스타일링에서 스타일요소를 추가로 넣어서 확장시킬 수 있다.
const StyledDiv = styled.div`  //기본스타일링
	width: 100px;
    	height: 50px;
`

const WhiteDiv = styled(StyledDiv)`  // 기본스타일링에서 확장1
	background-color: white;
`

const BlackDiv = styled(StyledDiv)` //기본스타일링에서 확장2
	background-color: black;
`

 

  • 선택자 스타일링 : 자식요소를 선택해서 스타일링을 하고싶다면.. ${} 를 사용하여 자식요소를 선택할 수 있다. 
const Memo = styled.div`
    width:300px;
    height:500px;
`

const MainContainer = styled.section`
    display:flex;
    width:100vw;
    ${Memo} {  // -> ${} 를 사용해서 자식요소의 스타일링을 추가할 수 있다.
      background-color:black;
      color: white;
    }
`

const ShadowMemo = styled(Memo)`
    box-shadow: 2px 4px 8px;
`

funtion Section2 () {
  return(
    <>
    <MainContainer>
      <Memo>Lorem Ipsum</Memo>  // -> 이부분만 스타일링을 추가해주고 싶다면 
      <ShadowMemo>Lorem Ipsum</ShadowMemo>
    </MainContainer>
      <Memo>Lorem Ipsum</Memo>
    </>
  )
}

 


3.  기타 환경 셋팅하기

 

🌈  styled-components 코드 자동 완성 플러그인

css 스타일코드를 자동완성을 해주는 플러그인이다. 

 

익스텐션에서 vscode-styled-components 검색후 설치

 

 

🌈  css 노멀라이징 라이브러리 (styled-reset)

(1)설치하기

// yarn
$ yarn add styled-reset

// npm 
$ npm i styled-reset

(2) 적용방법

  1.  import를 시켜주고
  2. 컴포넌트 내부 상단에 <Reset />을 적어준다.
import * as React from 'react'
import { Reset } from 'styled-reset' //->1.적어주기

const App = () => (
  <React.Fragment>
    <Reset />  //->2.적어주기 
    <div>Hi</div>
  </React.Fragment>
)

 

🌈  react-icons 아이콘 사용하기

폰트속성을 가진 다양한 아이콘을 사용할 수 있다.

라이브러리를 설치한 후 아래 사이트에서 아이콘이름을 import해주면 된다.

https://react-icons.github.io/react-icons

 

React Icons

React Icons Include popular icons in your React projects easily with react-icons, which utilizes ES6 imports that allows you to include only the icons that your project is using. Installation (for standard modern project) npm install react-icons --save Usa

react-icons.github.io

(1)설치하기

npm install react-icons --save // npm
yarn add react-icons // yarn

(2)import 하기, 사용하기

import {아이콘이름} from 'react-icons/fa';

// 사용할땐 컴포넌트형태로 사용
<아이콘이름/>

 

728x90
320x100

'front-end > CSS' 카테고리의 다른 글

[SCSS] SCSS 사용하기  (0) 2022.11.29
[CSS] all 속성 - 스타일 초기화하기  (0) 2022.03.06

댓글