Styled-components 기억하기

이경준·2021년 1월 6일
1

React를 학습하던 중 모듈 시스템의 중요성을 계속 깨닫고 있다. 익숙하지 않은 방식들에 시간이 오래 걸리긴 하지만 반복적으로 사용하고 익숙해지면 분명 세분화된 폴더트리 구성에 훨씬 편해질 것이다.

styled-component로 css만들기

1) styled-component 설치하기

//terminal
npm i styled-components 

//package.json
"dependencies": {
    "@testing-library/jest-dom": "^5.11.8",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.6.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    //-----
    "styled-components": "^5.2.1",
    //-----
    "web-vitals": "^0.2.4"
  },

윈도우 터미널창에 styled-components를 먼저 설치해준다.
package.json파일의 dependencies를 확인해보면 버전이 설치된 것을 확인 할 수 있다.

2) 폴더구성

-components
--header
---Header.jsx
---Header.style.jsx
--nav
---Nav.jsx
---Nav.style.jsx

컴포넌트별로 폴더를 만들어서 style파일과 함께 구성하여야 추후 유지보수가 편리해진다.

3) 기본 사용문법

//Header.style.jsx
import Styled from "styled-components"

export const HeaderContainer = Styled.header`
  width: 1080px;
  height: 150px;
  background-color: dodgerblue;
`
export const title = Styled.h1`
  font-size:20px;
  color:white;
`

//Header.jsx
import * as Styled from "./Header.style"

<Styled.HeaderContainer>
  <Styled.title>
    좋은 하루!
  </Styled.title>
</Styled.HeaderContainer>

es6문법인 import와 export로 내보내고 가져와서 사용 가능하다.
style파일에서는 styled-components를 먼저 import해야 사용 가능하며 ``를 사용하여 css문법을 작성 할 수 있다. 작성한 변수는 export하여 jsx파일에서 태그 형식으로 사용 가능하다.

4) 공통 css 사용하기

const CommonButton = Styled.button`
  background-color:#146af0;
  width: 200px;
  height:49px;
  border-radius:99px;
  outline:none;
  border:none;
  font-size:.95rem;
  font-weight:bold;
  color:white;
`;

const NewButton = Styled(CommonButton)`
  background-color: red;
`

워와 같이 ( )안에 선언된 변수를 넣으면 style값을 모두 가져오며 추가로 작성한 style코드는 덮어씌어지거나 추가할 수 있다.

5) props 받아서 style주기

//Header.style.jsx
export const title = Styled.h1`
  color: ${({color}) => color || "blue"}
`
//Header.jsx
<Styled.title color={{color: "red"}}>타이틀</ Styled.title>
//빨간색 글씨
<Styled.title>타이틀</ Styled.title>
//파란색 글씨

6) 공통 css 받아서 hover 주기

//Header.style.jsx
const HoverBlue = `
  transition: 0.3s;
  &:hover {
    color: #146af0;
  }
`;

export const UtilFont = Styled.span`
  font-size:.9rem;
  color:black;
  ${HoverBlue}
`;

반복적인 css코드는 ``만 붙여서 작성한 후 ${ }안에 적으면 반복적으로 사용이 가능하다. 또한 hover는 $:hover{ }안에 사용 가능하다.

7) 에니메이션 주기

import {keyframes} from "styled-components";

const boxAnimation = keyframes`
  0% {
    transform: rotate(0deg)
  }
  100% {
    transform: rotate(360deg)
  }
`

const isBox = Styled.div`
  background-color: dodgerblue;
  animation: ${boxAnimation} 2s infinite linear;
`

keyframes를 import해야 사용 가능하다.

8) media query 사용하기

const device = {
  smallDesktop: `(max-width: 1080px)`,
  laptop: `(max-width: 780px)`,
  phone: `(max-width: 480px)`,
}

export const Button = Styled.button`
  width: 100px;
  height: 100px;
  @media ${device.laptop} {
    width: 80px;
    height: 80px;
  }
  @media ${device.phone} {
    width: 50px;
    height: 50px;
  }
`

다른 파일에 미리 사이즈를 지정해 놓고 쓰면 매번 가져와서 사용이 가능하며 @media${사이즈}{ }로 사용이 가능하다.

9) scss형식으로 작성하기

export const TitleFirst = Styled.li`
  width:50%;
  .shopping-title {
    ${NavTop}
    background-color:#146af0;
    span {
      color: white;
      font-weight:bold;  
    }
  }
  ul {
    display: flex;
    justify-content:space-between;
    align-items:center;
    padding:5% 0;
    .shopping-list {
      width:25%;
      display:flex;
      flex-direction:column;
      align-items:center;
      border-right: 1px solid rgba(1,2,1,0); 
      border-left: 1px solid #8b5959; 
      p {
        font-size:.85rem;
        color: #146af0;
        font-weight:bold;
      }
      ul {
        display:flex;
        flex-direction:column;
        li {
          font-size:.8rem;
        }
      }
    }
  }
`;

scss형식이 가독성이 훨씬 좋다고 생각한다. styled-components에서도 scss처럼 트리형태로 작성이 가능하다.

아직 javascript를 같이 사용하는것에 익숙하지 않으니 반복학습이 필요하다.

profile
내가 기억하기위한 블로그

0개의 댓글