All Articles

wecode 7주차_5일 TIL_styled-component에 대해 알아보자!

image.png

CSS tool에는 다양한 것들이 있는데, 그 중에서 가장 최신의 것인 Styled Component에 대해서 알아볼 것이다!

설치

터미널에 yarn add styled-components 입력 고고! 일반적인 경우라면 저 명령어면 되겠지만~ 나는 우분투유저니까 sudo 필수! 외쳐! 갓수도~~~

적용

import 받아오는 위쪽라인에 import styled from "styled-components" 이거 한줄 추가하기! 이것만 있으면 CSS파일을 import 하지 않아도 된다. 왜냐? 우리는 js 파일에 styled-component 태그를 직접적으로 적용시킬거거든

image.png

이 버튼 두개를 만들기 위해선… 버튼태그와 js파일만 필요하다. css는 없어도 된다 씬기씐기!

import React, {Component} from "react";
import styled from "styled-components"

class Air extends Component {
    render() {
        return (
        <Container>
            <Button yes>Yes</Button>
            <Button no>Nope</Button>
        </Container>
        )
    }
}

const Container = styled.div`
width: 100%;
background-color: #bdbdbd;
`
const Button = styled.button`
width: 100px;
border-radius: 50px;
padding: 5px;
color: white;
background-color : ${props=> props.yes ? "blue" : "red"}
`

export default Air;

같은 Button 태그여도 색깔을 다르게 주고싶다면 꺽쇠 안에 특정 이름을 주고, 그걸 props로 넘기면 같은 코드를 두번씩 안 써도 된다! 오!! 이것도 컴포넌트라고 props로 넘기는게 가능하다니.. 넘나 신기한 것

근데 약간 아쉬운건 개발자도구를 까보면…

image.png

이렇게 전혀 알수없는 클래스명이 나온다는 점…☆

전역에 효과주기

image.png

배경색을 한번 입혀봤더니 넘나 margin이 제거 안된 것… 이걸 제거해주기 위해 우리는 명령어를 또 써줘야 한다!

import styled, { createGlobalStyle } from "styled-components" styled-components를 불러온 그 공간에 명령어 추가해주고

전역에 주고싶은 효과를 body에 넣어주면 된다.

const GlobalStyle = createGlobalStyle `
body {
    margin : 0;
    padding: 0;
    width: 100%;
    background-color: #bdbdbd;
}`

잠깐! 여기서 끝이 아니다. 이걸 또 태그로 써줘야지 적용이 됩니다요~

한 가지 주의사항!

좋은 예

	<>
 	<GlobalStyle />
       <Button yes>Yes</Button>
       <Button no>Nope</Button>
    </>

나쁜 예

	<>
 	<GlobalStyle>
    	<Button yes>Yes</Button>
      	<Button no>Nope</Button>
     </GlobalStyle>
    </>

처음엔 뭣도 모르고 저 태그 사이에 다른 요소를 넣는 식으로 했는데 나쁜 예처럼 하면 화면이 회색으로만 가득 찬다. 버튼은 보이지 않는다!! Sass의 영향 때문인지 태그 안에 태그를 가둬야 마음의 안정을 얻게 되는데 자꾸..ㅋㅋㅋ GlobalStyle은 그냥 좋은예처럼 자체로 괄호를 닫고 쓰자!

styled-reset

우리가 SASS 쓸 땐 reset.css 파일을 따로 만들어줬었는데.. styled-component에선 라이브러리로 다운을 받고 GlobalStyle 태그만 붙여주면 된다!

사실 요곤 몰랐는데.. 권순규님의 블로그를 보고 알게 되었다! 링크는 여기 ☞ https://soongyu.github.io/posts/til-26-react-styled-components/

그러기 위해선 먼저 styled-reset을 깔아야 함. yarn add styled-reset

image.png

근데 또 에러가 나네? sudo를 썼는데도 에러가 남… 보니깐 10.0.0 이상의 node version이 필요한 것 같음. 그래서 업글함

image.png

n latest라는 명령어로 쉽게 업글 할 수 있는건데 허가거부… 이럴 땐 뭐다????? 외쳐! 갓 sudo!!!!!

image.png

node를 업글하고 나니 설치가 제대로 된다 와우!

import reset from "styled-reset" import 라인에 이거 추가해주고

GlobalStyle에 template literal을 이용해 reset을 불러오면 적용 끝~

const GlobalStyle = createGlobalStyle `
  ${reset};
body {
    margin : 0;
    padding: 0;
    width: 100%;
}`

withComponent

만약에 버튼인데 링크를 걸고 싶다면? const Anchor = Button.withComponent("a"); 이렇게 Button이라는 변수에 .withComponent를 쓴 다음 괄호 열고 원하는 html 태그이름을 넣어준다.

<Anchor href= "http://google.com" yes>Google it!</Anchor> 난 빨강색을 그다지 좋아하지 않기 때문에 위에서 설정한 파랑의 yes라는 값을 주었고 그 결과!

image.png 이런 결과가 뙇!

withComponent말고도 한 가지 방법이 더 있는데.. <Button as="a" href= "http://google.com">Google it!</Button> 속성값에 as="html태그명"을 쓰고 a니까 나는 href까지 써주면 withComponent때와 똑같은 버튼을 간단히 만들수 있다!

근데 저 밑줄도 너무 보기 싫고.. 옆의 버튼과 너무 다르게 못생겼다. 그럴때 쓸 수 있는게 또 있쥐

styled(어쩌구)

원래는 withComponent에 extend로 효과를 줬는데, 이제는 단순히

const Anchor = styled(Button)`
  text-decoration: none;
`;

styled(어쩌구)만 쓰면된다. 그니까 그 위의 withComponent는 굳이 안써도 된다는 말씀..! 결과는 아래와 같다~!

image.png

근데 as를 썼을 때는 디자인을 어떻게 바꿔야 할지… 이건 좀 더 찾아보고 나중에 글을 수정할 예정!

프론트앤드 기술의 변화는 정말정말정말 빠르다. https://formidable.com/blog/2019/upgrade-styled-components/ 요 사이트 들어가면 styled-component에서 사라진 것들과 새로 생긴 것들을 만나볼 수 있다.

Animation

먼저 import에 import styled, { createGlobalStyle , css, keyframes} from "styled-components" css와 keyframes 추가하기

그 다음 회전효과를 넣을건데, rotation이라는 변수를 다음과 같이 선언해주기

const rotation = keyframes`
from {
    transform: rotate(0deg);
}
to {
    transform: rotate(360deg);
}
`

그 다음 버튼의 styled-component 영역에 가서 효과를 준다. props.yes 즉 파랑색 버튼만 돌아가게 만들 것이다!

const Button = styled.button`
width: 100px;
border-radius: 50px;
padding: 5px;
color: white;
background-color : ${props=> props.yes ? "blue" : "red"}
${props => {
    if(props.yes) {
        return css `animation: ${rotation} 2s linear infinite`;
    }
}}

적용해보면 이렇게 뙇! 아주 잘 돌아간다. 예전에는 그냥 keyframe만 써도 됐지만, 요즘은 css까지 붙여줘야 한다고 ㅠㅠ

image.png

어찌됐든 잘 돌아가는거 확인쓰~ 애니메이션 넣기 성공쓰!

.attr

이번엔 input박스를 하나 만들건데… Input이라는 태그를 만드는건 아주 간단하게 할 수 있다 위에서 해왔던 것처럼! 근데 placeholder를 주고싶은데.. <Input placeholder="hello"/> 이렇게 쓰면 뭔가 지저분해보이고.. 그럴 때 쓸 수 있는 것이 바로 .attr이다!

const Input = styled.input.attrs({ placeholder: "hello" })`` 젤 뒤에 빽틱은 Input에 css 효과를 주기 위한것인데.. 아무효과를 안 주고 attribute 값만 줄때도 빽틱은 꼭 써줘야 에러가 나지 않는다.

image.png

짠. 이렇게 placeholder가 hello인 인풋박스 완성!

Mixin

SASS에서 써 봤던 Mixin을 styled-component에서도 동일하게 쓸 수 있다! 이걸 사용하려면 import에 css 값을 넣어줘야 한다. 그 담에

const DooriColor = css`
  color: white;
  background-color: paleturquoise;
  border-radius: 10px;
  border: none;
`

원하는 변수 이름 = css 라고 입력 후 빽틱을 열고 원하는 효과를 입력쓰

const Input = styled.input.attrs({
    placeholder: "hello"
})`
    ${DooriColor};
`

아까 만들었던 인풋박스의 빽틱 안에 DooriColor를 넣어주면…

image.png 이렇게 뙇! 공통적인 요소들은 Mixin을 이용해 효과를 한번에 주기 편할 것 같다

ThemeProvider

mixin이랑 비슷하게 ThemeProvider라는게 있다. 일단 코드 먼저 뿌려본다

import React, { Component } from "react";
import styled, { createGlobalStyle , ThemeProvider } from "styled-components"
import theme from "./theme";

const GlobalStyle = createGlobalStyle `
body {
    margin : 0;
    padding: 0;
    width: 100%;
}`

const Container = styled.div`
height: 100vh;
width: 100%;
background-color: palegreen`

const Card = styled.div`
  background-color: white;
`;

const Button = styled.button`
  border-radius: 20px;
  padding: 25px 15px;
  background-color: ${props => props.theme.successColor}
`;

const Form = () => (
  <Card>
    <Button>Hungry!</Button>
  </Card>
)

class Air extends Component {
    render() {
        return (
            <ThemeProvider theme={theme}>
             <GlobalStyle />
            <Container>
                <Form />
              </Container>
            </ThemeProvider>

        );
    }
}

export default Air;

오류 땜에 20분 정도 버렸다. 왜 오류가 났냐? 저 요소들을 감싸주는 전체 div를 만들지 않았기 때문… 그래서 Container태그를 다시 만들어주니 오류는 빠이염~

주목할 점들이 몇 가지 있다.

  • theme.js 폴더 만들고 import 받아오기. Button의 css부분을 살펴보면 알 수있다.
const theme = {
    mainColor: "yellow",
    dangerColor : "blue",
    successColor : "aliceblue",
};

export default theme;

나는 이렇게 만들었다.

  • 틀을 만들어서 컴포넌트로 재활용하기 틀을 만들어서 Form 이라는 변수를 선언하고 그걸 직접 태그로 적용할 수 있다는게 너무 신기씐기!
  • props로 theme에서 색깔 받아오기 전반적으로 styled-component를 쓰면 props 이용을 많이 하는 것 같다 오오!

Reference