본문 바로가기

What I Learnd/TIL

TIL - TypeScript에서 Styled Components 라이브러리 사용하기 step by step

1. @type/styled-components 패키지 설치

npm install styled-components @types/styled-components
# 또는
yarn add styled-components @types/styled-components

 

2. tsconfig.json 설정

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "*": ["types/*"]
    }
  }
}

: TypeScript가 모듈 해석 시 타입 선언 파일을 찾을 수 있도록 하는 설정

 

3. 똑같이 import styled from 'styled-components' 임포트하고 사용!

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

// 인터페이스를 사용하여 컴포넌트에 전달될 속성들의 타입을 정의
interface ButtonProps {
  primary?: boolean;
  disabled?: boolean;
}

// Button 컴포넌트를 styled-components를 사용하여 스타일링
const Button = styled.button<ButtonProps>`
  padding: 10px 20px;
  background-color: ${props => (props.primary ? 'blue' : 'gray')};
  color: white;
  font-size: 16px;
  border: none;
  border-radius: 4px;
  cursor: ${props => (props.disabled ? 'not-allowed' : 'pointer')};
  opacity: ${props => (props.disabled ? 0.5 : 1)};
`;

const App = () => {
  return (
    <div>
      <Button>기본 버튼</Button>
      <Button primary>주요 버튼</Button>
      <Button disabled>비활성 버튼</Button>
    </div>
  );
};

export default App;