ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [React.js] Styled Components 간단 정리 [Basic]
    development/React 2021. 6. 24. 22:37

    Styled components 로고

    이번 포스팅에서는 styled-components 라이브러리의 기본적인 문법과 간단한 사용법에 대해 다루고자 합니다.

    공식 문서의 글을 좀 더 단순하고 쉽게 표현한 글 입니다. 좀 더 심화된 내용은 공식 문서를 참조하시면 좋습니다. [공식 문서]

    (본 글은 이전에 업로드 되었던 내용을 좀 더 보기좋게 다듬어 재 업로드 한 글입니다.)

    className의 명시적인 주입 없이 컴포넌트를 만들고 스타일을 적용하기

    import React from 'react';
    import styles from './styles.css';
    
    /* ... */
    
    <button className={"any-classname"}>Default CSS</button>

    기본적인 CSS를 이용한다고 가정했을때, 위와 같이 사용하려는 스타일을 classname을 사용해서 일일이 지정해줘야 합니다.

    그닥 나쁜 경우는 아니지만, CSS 내의 Classname 중복 문제도 걱정해야 하고. Props를 받아서 처리 하기도 번거롭습니다.

    styled-components로 작성해보기

    import React from 'react';
    import styled from 'styled-components';
    
    const Button = styled.button`
        {...any-button style};
    `;
    
    /* ... */
    
    <Button>Styled Button</Button>

    위와 같이 처리하면 classname의 고질적인 문제를 훨씬 멋지게 회피 할 수 있습니다.

    Styled component에 Props를 전달하기

    우리는 버튼을 만들고자 하고, props로 'color'라는 값이 넘어오면 props의 color값을 Background 값으로 사용하고자 합니다.

    그리고 props의 'color' 라는 값이 없다면 노란 색깔로 Background를 칠할 것이라는 조건부 스타일링을 아래와 같이 할 수 있습니다.

    const Button = styled.button`
        background: ${props => props.color ? props.color : 'yellow'};
    `;
    
    {...}
    
    <Button>Default yellow button</Button>
    <Button color={"red"}>Custom red button</Button>

    Styled component를 상속받기

    새로이 제작한 Button 이라는 컴포넌트를 상속받아서 RedButton을 만들고자 한다면, 아래와 같이 할 수 있습니다.

    const Button = styled.button`
        background-color: yellow;
      border: 1px solid red;
      color: green;
    `;
    
    // extends <Button />
    const RedButton = styled(Button)`
        &:hover {
            background-color: red;
        }
    `;
    
    <Button>Default Button</Button>
    <RedButton>Red Button!!!!!</RedButton>

    As 속성

    만약 Button 컴포넌트의 스타일은 그대로 쓰고싶지만, 태그의 종류를 button이 아닌 a 태그로 바꾸고 싶을땐 'as' 속성을 이용하여 아래와 같이 구현할 수 있습니다.

    {...}
    
    <Button as={"a"} href={"/yeah"}>I am a tag!</Button>

    Attributes 삽입하기

    attrs 라는 속성을 사용해서 고정되는 Props나 다이나믹한 Props, 기본 Tag의 props 등을 전달할 수 있습니다.

    const Input = styled.input.attrs(props => ({
      // 고정적인 Props를 전달할 수 있습니다.
      type: "password",
    
      // 혹은 다이나믹한 Props도 전달할 수 있습니다.
      size: props.size || "100px",
    }))`
        width: ${props => props.size};
    `;
    
    <Input placeholder={"default size input!"}  />
    <Input placeholder={"bigger size input!"} size={"200px"} />

    애니메이션

    classname과 마찬가지로 이름 충돌을 피하기 위해서 전역으로 선언하는 animation을 추천하지 않습니다.

    그에 대한 해결책으로 styled components에선 keyframes 라는 것을 지원합니다.

    const colorChange = keyframes`
        from {
            background-color: red;
        }
    
        to {
            background-color: yellow;
        }
    `;
    
    const ColorButton = styeld.button`
        animation: ${colorChange} 1.5s linear infinite;
        width: 10rem;
        height: 3rem;
    `;
    
    {...}
    
    <ColorButton>화려한 버튼입니다!</ColorButton>

    Styled comonents를 만들때 금기사항

    절대로 render 안쪽에 Styled component를 선언해서는 안됩니다. 리렌더링이 될 때 마다 요소를 새로 제작하기 때문에, 매우 비효율적인 컴포넌트가 완성될 수 있습니다.

    금기시 되는 코드

    import React from 'react';
    import styled from 'styled-components';
    
    const AnyComponent = () => {
        // 절대 여기서 선언하면 안됩니다!
        const Button = styled.button`
            {button styles...};
        `;
    
        return (
            <Button>Bad!!!!</Button>
        );
    }
    
    return AnyComponent;

    정상적인 코드

    import React from 'react';
    import styled from 'styled-components';
    
    const Button = styled.button`
        {button styles...};
    `;
    
    const AnyComponent = () => {
        return (
            <Button>Good!</Button>
        );
    }
    
    return AnyComponent;

    마치며

    여기까지 가장 Basic한 styled components의 기본기를 정리해보았습니다.

    기본기라곤 하지만, 사실 위에 작성된 내용만 완전히 이해하셔도 이 라이브러리를 사용하는 것에 큰 무리가 없을 것이라고 예상합니다.

    이해가 안되시는 부분이나 잘못된 내용이 있다면 코멘트 남겨주시면 최대한 빠른 답변 드리겠습니다. 감사합니다.

Designed by Tistory.