Styled-Component란?
Javascript 파일 내에서 CSS를 사용할 수 있게 해주는 대표적인 CSS-in-JS 라이브러리로 React 프레임워크를 주요 대상으로 한 라이브러리이다.
설치
$ npm install --save styled-components
기본문법
const {위에서 지정해준 component명} = styled.{태그명} ``;
- HTML 엘리먼트를 스타일링
- 모든 알려진 HTML 태그에 대해서 이미 속성이 정의되어 있기 때문에 해당 태그명의 속성에 접근합니다.
import styled from "styled-components";
styled.button`
// <button> HTML 엘리먼트에 대한 스타일 정의
padding: 4em;
background: papayawhip;
`
- React 컴포넌트를 스타일링
- 해당 컴포넌트를 임포트 후 인자로 해당 컴포넌트를 넘김.
`import styled from "styled-components";
import Button from "./Button";
styled(Button)`
// <Button> React 컴포넌트에 스타일 정의
`;`
결과
예를 들어, 다음과 같이 Styled Components로 작성된 JavaScript 코드는
import styled from "styled-components";
styled.button`
font-size: 1rem;
`;
아래 CSS 코드가 적용된 <button> HTML 엘리먼트를 만들어낸다.
button {
font-size: 1rem;
}
ex) 고정 스타일링
위에서 배운 Styled Components 문법을 이용해서 React로 작성된 버튼 컴포넌트를 스타일
import React from "react";
import styled from "styled-components";
const StyledButton = styled.button`
padding: 0.375rem 0.75rem;
border-radius: 0.25rem;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
color: gray;
backgroud: white;
`;
function Button({ children }) {
return <StyledButton>{children}</StyledButton>;
}
이제 스타일이 적용된 이 버튼 컴포넌트를 다른 React 컴포넌트에서 다음과 같이 사용할 수 있다.
import Button from "./Button";
<Button>Default Button</Button>;
ex)의 결과
브라우저에서 소스 보기를 해보면 다음과 같이 <button> HTML 엘리먼트에 Styled Components가 자동으로 생성해준 클래스 이름이 적용되었음을 알 수 있다.
<button class="sc-kgAjT beQCgz">Default Button</button>
한편, 내부 스타일시트를 확인해보면 클래스 선택자(class selector)로 적용된 스타일이 위에서 Styled Components로 삽입한 스타일과 동일함을 알 수 있다.
.beQCgz {
padding: 0.375rem 0.75rem;
border-radius: 0.25rem;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
color: gray;
background: white;
}
ex) 가변 스타일링
예를 들어, 버튼의 글자색과 배경색을 props따라 바뀌도록 위에서 작성한 예제 코드를 변경해보자면, 자바스크립트의 || 연산자를 사용하여 props이 넘어오지 않은 경우, 기존에 정의한 기본 색상이 그대로 유지되도록 한다.
import React from "react";
import styled from "styled-components";
const StyledButton = styled.button`
padding: 0.375rem 0.75rem;
border-radius: 0.25rem;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
color: ${(props) => props.color || "gray"};
background: ${(props) => props.background || "white"};
`;
function Button({ children, color, background }) {
return (
<StyledButton color={color} background={background} Î>
{children}
</StyledButton>
);
}
import Button from "./Button";
<Button color="green" background="pink">
Green Button
</Button>;
ex) 가변 스타일링 2
prop에 따라 바꾸고 싶은 CSS 속성이 위와 같이 하나가 아니라 여러 개일 경우가 있다. 이럴 경우, Styled Components에서 제공하는 css 함수를 사용해서 여러 개의 CSS 속성을 묶어서 정의할 수 있다.
primary prop이 넘어온 경우, 글자색을 흰색, 배경색과 경계색은 남색으로 변경하고 싶다면 다음과 같이 예제 코드를 수정할 수 있다. 이번에는 자바스크립트의 && 연산자를 사용해서, primary prop이 존재하는 경우에만 css로 정의된 스타일이 적용되도록 하였다.
import React from "react";
import styled, { css } from "styled-components";
const StyledButton = styled.button`
padding: 0.375rem 0.75rem;
border-radius: 0.25rem;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
${(props) =>
props.primary &&
css`
color: white;
background: navy;
border-color: navy;
`}
`;
function Button({ children, ...props }) {
return <StyledButton {...props}>{children}</StyledButton>;
}
[참고]
'개발몰입과정 개념스터디 > 4차' 카테고리의 다른 글
CSR, SSR (React, Next.js) (0) | 2022.02.07 |
---|---|
PWA란? (0) | 2022.02.07 |
Tailwind CSS이란? (0) | 2022.02.05 |
SCSS (CSS Modules)란? (0) | 2022.02.05 |
SEO와 SSG, 그리고 Gatsby.js (0) | 2022.02.05 |