개발 노트

Styled-Component 본문

React

Styled-Component

알 수 없는 사용자 2022. 11. 11. 16:00

01. Styled-Component?

모던 자바스크립트 라이브러리(React,Angular,Vue 등)가 인기를 끌면서 여러 개의 컴포넌트로 분리하고, 각 컴포넌트에 HTML, CSS, JavaScript를 몽땅 때려 박는 패턴이 많이 사용되고 있다.

React는 JSX를 사용해서 이미 JavaScript가 HTML을 포함하고 있는 형태를 취하고 있는데,

여기에 CSS-in-JS 라이브러리만 사용하면 CSS도 손쉽게 JavaScript에 삽입할 수 있다.

 

styled-component는 css를 js에 쉽게 삽입할 수 있도록 도와주는 CSS-in-JS라이브러리 중 가장 널리 사용되고 있는 라이브러리이다.

 

02. 사용법

일단 npm 패키지를 설치해야한다.

npm i styled-components

기본 문법

일단 기본적으로 styled-components 패키지에서 styled함수를 import한다.

import styled from "styled-components";

기본 문법은 HTML 엘리먼트, React 컴포넌트 중 어떤 것을 스타일링 하느냐에 따라 다르다.

  • HTML element를 스타일링 할 때는 알려진 HTML 태그에 대해서 이미 속성이 정의되어 있기 때문에 해당 태그명의 속성에 접근한다.
import styled from "styled-components";

const SimpleButton = styled.button`
  color: white;
  background-color: green;
`;
  • React 컴포넌트를 스타일링 할 때는 해당 컴포넌트를 import 후 argument로 해당 컴포넌트를 넘기면 된다.
import styled from "styled-components";

styled(Button)`
	color: white;
    background-color : green;
`;
import Button from "./Button"

<Button>StyledButton</Button>

두가지 문법 모두 Tagged Template Literals에 따른다.

Tagged Template Literals는 쉽게 보자면 `string text ${expression} string text` <- 이거다.

후에 styled 함수는 스타일이 적용된 결과물을 리턴한다.

 

이런 식으로 styled components를 이용하면 JavaScript 파일마다 고유한 CSS 네임 스페이스를 부여해주기 때문에,

각 React 컴포넌트에 완전히 격리된 스타일을 적용할 수 있게 된다.

 

가변 스타일링

styled components는 react 컴포넌트에 넘어온 props에 따라 다른 스타일을 적용할 수 있다.

 

const PrimaryButton = styled.button`
  color: ${(props) => (props.primary ? "white" : "black")};
  background-color: ${(props) => (props.primary ? "blue" : "black")};
`;

위처럼  Tagged Template Literals 사용하기 때문에 함수를 넣을 수 있고 조건식을 사용해 primary가 props에 있다면 css를 어느 것으로 적용한다는 식을 세울 수 있다.

const StyledButton = styled.button`
  color: ${(props) => props.color || "gray"}; 기본색상 gray
  background: ${(props) => props.background || "white"}; 기본색상 white
`;
import Button from "./Button";
<Button color="green" background="pink">
  Green Button
</Button>;

자바스크립트의 ||연산자를 사용하여 props가 넘어오지 않은 경우, 기존에 정의한 기본 색상이 그대로 유지되도록 한다고 적어줄 수 있다.

 

**

function Button({ children, ...props }) {
  return <StyledButton {...props}>{children}</StyledButton>;
}

참고로 넘겨야할 prop 값이 많아질 경우, 위와 같이 ...props 구문을 사용해서 children 외에 모든 prop을 간편하게 전달할 수 있다.

 

03. 또 하나의 기능

styled-components는 이미 존재하는 component를 wrapping(감싸서)해서 새로운 스타일이 적용되는(상속받는) 새로운 component를 만들 수 있다.

const SimpleButton = styled.button`
  color: white;
  background-color: green;
`;

const LargeButton = styled(SimpleButton)`
  font-size: 50px;
`;

위와 같이 작성한다면 LargeButton은 color,background-color를 상속받고 size가 커진 button이 된다.

'React' 카테고리의 다른 글

React - zustand middleware - persist  (0) 2022.11.16
React - uuid Library  (0) 2022.11.16
React - Routing  (0) 2022.11.11
The React Hooks - useRef Hook  (0) 2022.11.11
The React Hooks - useMemo  (0) 2022.11.11