Styled-components

@t189216·2024년 3월 12일

😎 프론트엔드

목록 보기
29/31

Styled-components


Styled-components는 CSS 문법을 그대로 사용하면서 결과물을 스타일링된 컴포넌트 형태로 만들어주는 오픈소스 라이브러리입니다. 컴포넌트 개념을 사용하기 때문에 React 개발에 많이 사용됩니다. styled-components 는 tagged template literal을 사용하여 구성요소의 스타일을 지정합니다.

Styled-components 설치

# npm을 사용하는 경우
npm install --save styled-components

# yarn을 사용하는 경우
yarn add styled-components

template literal

literal을 템플릿 형태로 사용하는 자바스크립트 문법으로 역따옴표(백틱, `)을 사용하여 문자열을 작성하고 그 안에 대체 가능한 expression을 넣습니다. 여기서 expression을 대체라는 뜻을 가진 Substitution이라고 부릅니다.

literal ?

literal은 프로그래밍에서 소스 코드에 고정된 값을 말합니다. 상수와는 다른 개념입니다.

// 정수 리터럴 (Integer literal)
const myNumber = 10;

// 문자열 리터럴 (String literal)
const myStr = 'Hello';

// 배열 리터럴 (Array literal)
const myArray = [];

// 객체 리터럴 (Object literal)
const myObject = {};

상수를 의미하는 const 을 사용하면 한 번 선언된 이후에는 값을 바꿀 수 없습니다.

template literal은 Untagged template literal과 Tagged template literal로 나뉩니다.

// Untagged template literal
// 단순한 문자열
`string text`

// 여러 줄(Multi-line)에 걸친 문자열
`string text line 1
string text line 2`

// 대체 가능한 expression이 들어있는 문자열
`string text ${expression} string text` 


// Tagged template literal
// myFunction의 파라미터로 expression으로 구분도니 문자열 배여롸 expression이 순서대로 들어간 형태로 호출됨
myFunction`string text ${expression} string text`

Tagged template literal 예시

const name = 'Ellie';
const region = '서울';

function myTagFunction(strings, nameExp, regionExp) {
    let str0 = strings[0];  // "제 이름은 "
    let str1 = strings[1];  // ", 사는 곳은 "
    let str2 = strings[2];  // "입니다."

    // 여기에서도 template literal을 사용하여 리턴할 수 있음
    return `${srt0}${nameExp}${str1}${regionExp}${str2}`
}

const output = myTagFunction`제 이름은 ${name}이고, 사는 곳은 ${region}입니다.`;

// 출력 결과 : 제 이름은 Ellie이고, 사는 곳은 서울입니다,
console.log(output);

참고 문서 - MDN : Template literals

styled-components 사용법

styled-components는 tagged template literal을 사용하여 CSS속성이 적용된 React 컴포넌트를 만들어줍니다.

import React from 'react';
import styled from "styled-components";

const Wrapper = styled.div`
    padding: lem;
    background: grey;
`;

백틱으로 둘러싸인 문자열 부분에 CSS 속성을 넣고 태그 함수 위치에는 styled.html 태그 형태로 사용합니다. 이렇게 하면 해당 엘리먼트 태그에 CSS 속성들이 적용된 형태의 React 컴포넌트가 만들어집니다.

styled-components의 props 사용법

import React from 'react';
import styled from "styled-components";

const Button = styled.button`
    color: ${props => props.dark ? "white" : "black"};
    background: ${props => props.dark ? "white" : "black"};
    border: 1px solid black;
`;

function Sample(props) {
    return (
        <div>
            <Button>Normal</Button>
            <Button dark>Dark</Button>
        </div>
    )
}

export default Sample;

styled-component를 사용하는 부분의 CSS 속성을 보면 내부에 props가 사용된 것을 확인할 수 있습니다. 여기서 사용된 props는 해당 컴포넌트에 사용된 props를 의미합니다.

styled-components의 스타일 확장하기

import React from 'react';
import styled from "styled-components";

// Button 컴포넌트
const Button = styled.button`
    color: grey;
    border: 2px solid palevioletred;
`;

// Button에 style이 추가된 RoundedButton 컴포넌트
const RoundedButton = styled(Button)`
    border-radius: 16px;
`;

function Sample(props) {
    return (
        <div>
            <Button>Normal</Button>
            <RoundedButton>Rounded</RoundedButton>
        </div>
    )
}

export default Sample;

Button 컴포넌트는 HTML의 버튼 태그를 기반으로 만들어진 단순한 버튼입니다. RoundedButton 컴포넌트를 자세히 보면 HTML 태그가 빠져있고 Button 컴포넌트가 괄호로 둘러싸인 채로 들어가 있는 것을 볼 수 있습니다. 이것이 다른 컴포넌트의 스타일을 확장해서 사용하는 부분입니다.

공식 문서 - styled-components

vscode-styled-components

vscode에서 styled-components를 사용할때 자동완성 기능과 코드 하이라이팅 기능을 제공합니다.

profile
Today I Learned

0개의 댓글