Styled Component

Jean Young Park·2023년 1월 17일
0

react

목록 보기
19/32

Styled Component

Styled Component는 React의 Css-in-JS 라이브러리 중 하나이다. Styled Components는 컴포넌트 기바의 스타일링을 쉽게 구현할 수 있도록 해주며, CSS를 작성하는 것과 유사한 방식으로 스타일링을 할 수 있다.

Styled Components의 장점 중 하나는 컴포넌트 기반의 스타일링이 가능하다는 점이다. 각각의 컴포넌트에 스타일을 적용하기 때문에 CSS 클래스명을 고유하게 만들 필요가 없으며, 전역 스타일이 충돌하는 문제도 해결할 수 있다.

또한, Styled Components는 JavaScript 코드 내에 CSS를 작성하기 때문에 CSS 파일을 별도로 로드할 필요가 없어서 네트워크 로딩 시간을 줄일 수 있다. 또한, 동적으로 스타일을 적용하기 쉬우며, 조건부 스타일링도 간단하게 구현할 수 있다.

예시

import styled from 'styled-components';

const Button = styled.button`
  background-color: #2ecc71;
  color: white;
  font-size: 16px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;

  &:hover {
    background-color: #27ae60;
  }
`;

function App() {
  return (
    <div>
      <Button>Click me!</Button>
    </div>
  );
}

하지만 Styled Components는 하나의 파일에 CSS와 컴포넌트를 함께 작성하기 때문에, 파일이 커지면 복잡해질 수 있다. 따라서, 파일 크기를 줄이기 위해 스타일과 컴포넌트를 분리하여 별도의 파일로 작성하는 것이 좋다. 이를 위해서는 styled-components 라이브러리의 createGlobalStylecss API를 사용할 수 있다.

createGlobalStyle

전역 스타일을 쉽게 작성할 수 있도록 해주는 API이다. 이를 사용하면 전체 애플리케이션에서 사용할 스타일을 별도의 파일로 분리하여 작성할 수 있다.

예시

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    background-color: #f5f5f5;
    font-family: 'Helvetica Neue', sans-serif;
    font-size: 16px;
    color: #333;
  }
`;

function App() {
  return (
    <div>
      <GlobalStyle />
      <h1>Hello World!</h1>
    </div>
  );
}

css API

styled-components 라이브러리의 스타일링 API 중 하나로, 스타일 속성을 동적으로 생성할 수 있다. 이를 사용하면 스타일링 로직을 함수로 분리하여 재사용성을 높일 수 있다.

예시

import styled, { css } from 'styled-components';

const Button = styled.button`
  background-color: #2ecc71;
  color: white;
  font-size: 16px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;

  ${props =>
    props.primary &&
    css`
      background-color: #3498db;
      &:hover {
        background-color: #2980b9;
      }
    `}
`;

function App() {
  return (
    <div>
      <Button>Default</Button>
      <Button primary>Primary</Button>
    </div>
  );
}

스타일 속성을 동적으로 생성하고 싶을때도 컴포넌트 파일과 스타일 파일을 분리할 수 있다.
아래 예시와 같이 속성을 전달

예시

// Button.js
import styled, { css } from 'styled-components';

const Button = styled.button`
  background-color: ${({ primary }) => (primary ? '#3498db' : '#2ecc71')};
  color: white;
  font-size: 16px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;

  ${({ primary }) =>
    primary &&
    css`
      &:hover {
        background-color: #2980b9;
      }
    `}
`;

export default Button;
// app.js
import Button from './Button';

function App() {
  return (
    <div>
      <Button>Normal Button</Button>
      <Button primary>Primary Button</Button>
    </div>
  );
}

export default App;

https://styled-components.com/docs/basics

  • 설치 방법
    npm : npm install --save styled-components
    yarn : yarn add styled-components

0개의 댓글