[TS] TypeScript에서 Styled-component 사용하기

MiMi·2022년 5월 19일
17

📘TypeScript

목록 보기
5/6
post-thumbnail

styled-components 설치

npm i styled-components

타입스크립트 - 타입정의 받기

npm i -D @types/styled-components

글로벌스타일 적용하기

createGlobalStyled으로 전역스타일 설정

// global-style.ts
import { createGlobalStyle } from 'styled-components';

// 외부에서 import 할거니까 모듈 내보내자~!
export const GlobalStyle = createGlobalStyle`
  /* 그밖에 글로벌 스타일 작성하기  */
`;

// 최상위 컴포넌트 : App.js 또는 index.js 등등 원하는 최상위에 코드 추가 
import {GlobalStyle} from '파일경로/global-style.ts'

const App = () => (
  <>
    <GlobalStyle /> // 여기에 글로벌-스타일-컴포넌트 위치
    <div>여기는 최상위 컴포넌트</div>
  </>
);

스타일 작성하기

props를 styled-component에 넘겨줄 때 타입을 지정해주지 않으면 오류가 난다.

//text.ts
<Text done={done}>{text}</Text>
//testStyle.ts
//이렇게 짜면 오류
export const Text = styled.div`
  flex: 1;
  font-size: 21px;
  color: #495057;
  ${({ done }) =>
    done &&
    css`
      color: #ced4da;
    `}
`;

//이렇게 하면 해결
export const Text = styled.div<{ done: boolean }>`
  flex: 1;
  font-size: 21px;
  color: #495057;
  ${({ done }) =>
    done &&
    css`
      color: #ced4da;
    `}
`;

1. 단일 props 사용시

// styled-components에 1개 props 타입지정
// const Container = styled.div< {프롭스명 : 타입지정} >`
const Container = styled.div< { age : number } >`
  color: ${(props) => (props.age > 20 ? 'red' : 'gray')};
`;

2. 다수 props 사용시 : interface 작성

// Container styled-components에 적용할 interfacer를 작성
interface Container extends 상속타입 {
  isActive: boolean;
  age: number;
  프롭스명: 타입지정;
}
// styled-components에 interface 타입 지정하기
const Container = styled.div<Container>`
  color: ${(props) => (props.age > 20 ? 'red' : 'gray')};
  background-color: ${(props) => (props.isActive ? 'red' : 'gray')};
`;

3. 상속 컴포넌트에 타입지정

// 상속컴포넌트의 타입 상속받기
interface Container {
  isActive: boolean;
  age: number;
  프롭스명: 타입지정;
}

// 상속받은 컴포넌트에 타입 추가하기
const Container = styled(상속받을 컴포넌트명)<Container>`
  color: ${(props) => (props.age > 20 ? 'red' : 'gray')};
  background-color: ${(props) => (props.isActive ? 'red' : 'gray')};
`;

참고문헌

profile
이제 막 입문한 코린이 -> 이전중 https://mimi98.tistory.com/

0개의 댓글