프로그래밍/React

Styled-Components With TS(theme, globalStyle)

수박수박좋다 2021. 6. 12. 14:29
반응형

Styled-Components With TS(theme, globalStyle)


TypeScript

TS에 Styled-Components를 적용해보자

설치

npm install @types/styled-components


1. 테마

공통적으로 사용되는 스타일을 테마로 묶어서 코드일관성을 지킬 수 있도록 한다.

이를 위해 먼저 타입선언과 테마를 작성해야한다.

1.1 styled.d.ts: 타입선언파일, 테마작성하기

.d.ts를 타입선언파일이라고 한다. TS코드의 타입 추론을 돕는 파일이다.

첫번째 단계는 styled.d.ts 라는 테마에 사용될 변수들의 타입들을 선언하는 파일을 만드는 것이다.

styled.d.ts 만들기
import 'styled-components';

// and extend them!
declare module 'styled-components' {
  export interface DefaultTheme {
    borderRadius: string;

    colors: {
      main: string;
      secondary: string;
    };
  }
}

위에서 만든 선언파일로 styled-components 모듈에 DefaultTheme 라는 이름의 인터페이스를 생성해 타입을 명시해놓는다.

테마를 작성할 때 import하여 테마안에 선언된 타입에 맞게 스타일을 작성해주면 된다.

테마 작성하기
import { DefaultTheme } from 'styled-components';

const myTheme: DefaultTheme = {
  borderRadius: '5px',

  colors: {
    main: 'cyan',
    secondary: 'magenta',
  },
};

export { myTheme };

직접 만들어본 예제

Styles/styled.d.ts 파일 작성

import "styled-components";

declare module 'styled-components' {
  export interface DefaultTheme {
    bgColors: {
      primary: string;
    }
  }
}

Styles/theme/DefaultTheme.ts 파일 작성

import { DefaultTheme } from 'styled-components';

const myTheme: DefaultTheme = {
  bgColors: {
    primary: 'blue',
  }
};

export { myTheme };

App.tsx

import styled, { ThemeProvider } from 'styled-components';
import { myTheme } from './styles/theme/DefaultTheme';

function App() {
  return (
    <div className='App'>
      <ThemeProvider theme={myTheme}>
        <Button>HELLO</Button>
      </ThemeProvider>
    </div>
  );
}

export default App;

const Button = styled.button`
  background-color: ${(props) => props.theme.bgColors.primary};
`;

주로 테마를 어떻게 구분해서 사용하지? 하나로써 사용하나?

2. Global Style

전역적으로 사용하는 스타일을 관리한다.

컴포넌트 형식으로 사용할 수 있다.

box-sizing 과 같은 baseCSS 규칙을 지정할 때 사용한다.

import {createGlobalStyle} from 'styled-components'

const GlobalStyle = createGlobalStyle`
    body {
        font-family : ...,
}
`
const App = () => {
  return (
      <div>
      <GlobalStyle/>
        <Button>1</Button>
        <Button>2</Button>
    </div>
  )
}

적용

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { ThemeProvider } from 'styled-components';
import { myTheme } from './styles/theme/DefaultTheme';
import { GlobalStyle } from './styles/GlobalStyle';

ReactDOM.render(
  <React.StrictMode>
    <>
      <GlobalStyle />
      <ThemeProvider theme={myTheme}>
        <App />
      </ThemeProvider>
    </>
  </React.StrictMode>,
  document.getElementById('root'),
);

참고
반응형