Styled-components 사용하기

choi yh·2023년 9월 14일
0
post-thumbnail

Styled-components로 React 스타일링하기

이번 프로젝트에서 정말 많이 사용한 styled component에 대해 알아보자.

Styled-components란?

styled-components는 JavaScript 안에서 CSS를 작성할 수 있게 해주는 CSS-in-JS 라이브러리이다.
컴포넌트와 스타일이 결합되어 독립적인 스타일 컴포넌트를 생성하며, 컴포넌트 단위로 스타일을 관리할 수 있다.

기본 사용법

styled-components를 사용하면 다음과 같이 컴포넌트에 직접 스타일을 적용할 수 있다:

import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
  padding: 10px;
`;

function App() {
  return (
    <div>
      <Button>Styled Button</Button>
    </div>
  );
}

위 예시에서 styled.button 구문 내부에 백틱(`)으로 감싼 CSS 코드를 작성한다. 이렇게 작성된 코드는 JavaScript 템플릿 리터럴로 해석되어 해당 요소에 적용될 스타일로 변환됨.

Props 전달하여 동적으로 스타일 변경하기

styled-components에서는 props를 전달하여 동적으로 스타일을 변경할 수 있음:

import styled from 'styled-components';

const Button = styled.button`
  background-color: ${props => props.primary ? 'blue' : 'gray'};
  color: white;
`;

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

위 예시에서 primary prop이 true로 설정되면 파랑색 배경색이 적용되고, 그렇지 않으면 회색 배경색이 적용된다.

글로벌 테마 설정 및 저장된 스타일 사용하기

글로벌 테마를 설정하고 저장된 스타일을 가져와서 사용하는 것도 가능하다:

import React from 'react';
import styled, { ThemeProvider } from 'styled-components';

// 글로벌 테마 설정
const theme = {
  colors: {
    primary: 'blue',
    secondary: 'gray',
  },
};

// 저장된 스타일 가져와서 사용하기
const Button = styled.button`
   background-color: ${props => props.theme.colors.primary};
`;

function App() {
   return (
     <ThemeProvider theme={theme}>
       <Button>Primary Button</Button>
     </ThemeProvider>
   );
}

위 예시에서 ThemeProvider를 사용하여 글로벌 테마를 설정한다. theme 객체에는 색상과 같은 변수들을 정의할 수 있으며, 이 변수들은 ${props.theme.colors.primary}와 같은 방식으로 참조하여 저장된 스타일을 사용할 수 있다.

재사용 가능한 CSS 조각 정의하기

styled-components의 장점 중 하나는 재사용 가능한 CSS 조각을 정의할 수 있다는 것입니다. 다음은 그 예시입니다:

import { css } from 'styled-components';

export const H1Style = css`
   font-size: ${(props) => props.theme.text.H1.size};
   font-weight: ${(props) => props.theme.text.H1.weight};
`;

// 다른 컴포넌트에서 사용하기
import styled from 'styled-components';
import { H1Style } from './textStyles'; // 경로는 실제 파일 위치에 따라 변경해주세요.

const Heading = styled.h1`
   ${H1Style}
`;

function MyComponent() {
   return (
     <div>
       <Heading>This is a heading</Heading>
     </div>
   );
}

export default MyComponent;

위의 예시에서 H1Style이라는 재사용 가능한 스타일 조각을 정의하고, 이를 MyComponent에서 사용하는 방법을 보여준다. H1Style을 임포트하고, ${H1Style} 형태로 styled.h1 내부에 삽입하여 해당 스타일 조각을 적용한다.

profile
더 높은곳으로 올라가기

0개의 댓글