so woon!

[TYPESCRIPT] typescript & styled-components 테마 연결 본문

Typescript/개념정리

[TYPESCRIPT] typescript & styled-components 테마 연결

xowoony 2023. 4. 1. 22:20

학습일 : 2023. 04. 01


이번에는 타입스크립트와 styled-components 테마를 연결해보고자 한다.



1. types/styled-components 설치
터미널에

npm install @types/styled-components 입력


=> 타입스크립트에게 styled-components가 무엇인지에 대해 설명해주기 위해 설치
=> https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/styled-components 참고

 

 

 


2. styled.d.ts 파일 생성
declaration 파일(.d.ts) 을 만든다 (선언 파일)
src폴더 밑에 styled.d.ts 라는 이름의 파일을 만들어준다.



그러고 나서 이 파일에
https://styled-components.com/docs/api#typescript 에 가서 


이걸 복사해와서 붙여준다.

// import original module declarations
import 'styled-components';

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

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



그런 다음 내가 설정할 styled components 테마 정의
내 맘대로 확장해나가면 된다.

 


<styled.d.ts>

import "styled-components";

// 여기서 속성을 추가해주면 theme.ts에도 똑같이 작성해주어야 한다.
declare module "styled-components" {
  export interface DefaultTheme {
    textColor: string;
    bgColor: string;
    btnColor:string;
  }
}



라고 설정해주도록 하겠다.

그런다음
src 폴더 안에
theme.ts 파일을 생성해주고

 


<theme.ts>

// 이곳에 테마를 작성한다.
// 테마를 생성함으로 인해 실수를 방지할 수 있다.
import { DefaultTheme } from "styled-components";

// 이 테마들은 styled.d.ts 파일 속 속성들과 같아야 한다.
// 작성해준 후 export 를 해준다.
export const lightTheme: DefaultTheme = {
  bgColor: "white",
  textColor: "black",
  btnColor: "red",
};

export const darkTheme: DefaultTheme = {
  bgColor: "black",
  textColor: "white",
  btnColor: "blue",
};



다 작성해주었으면 index.tsx로 간다.

 

<index.tsx>

<ThemeProvider> 안에 <App /> 을 감싼다.

<ThemeProvider> 는 styled-components로 부터 오는 하나의 컴포넌트이며

어떤 Theme (테마) 오브젝트를 필요로 한다.

<ThemeProvider> 안에 어떤 컴포넌트를 넣게 된다면

그 모든 컴포넌트들은 Theme Object에 접근할 수 있게 된다.

일단 밑에 코드를 보면 theme을 lightTheme으로 설정하였고

이 lightTheme은 theme.ts로부터 올 것이다.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { ThemeProvider } from "styled-components";

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);

root.render(
  <React.StrictMode>
    <ThemeProvider theme={lightTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

전체 코드를 살펴보면 관계성을 파악하는데에 좀 쉬울 것 같다.

 

 

전체 코드

<index.tsx>

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { ThemeProvider } from "styled-components";
import { darkTheme, lightTheme } from "./theme";

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);

root.render(
  <React.StrictMode>
    <ThemeProvider theme={lightTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

 

<App.tsx>

import styled from "styled-components";

// Container 컴포넌트
const Container = styled.div`
  background-color: ${(props) => props.theme.bgColor};
`;

// H1 컴포넌트
const H1 = styled.div`
  color: ${(props) => props.theme.textColor};
`;

function App() {
  return (
    <Container>
      <H1>Protected</H1>
    </Container>
  );
}

export default App;

 

 

<theme.tsx>

// 이곳에 테마를 작성함으로 인해 실수를 방지할 수 있다.
import { DefaultTheme } from "styled-components";

// 이 테마들은 styled.d.ts 파일 속 속성들과 같아야 한다.
// 작성해준 후 export 를 해준다.
export const lightTheme: DefaultTheme = {
  bgColor: "white",
  textColor: "black",
  btnColor: "red",
};

export const darkTheme: DefaultTheme = {
  bgColor: "black",
  textColor: "white",
  btnColor: "blue",
};

 

 

<styled.d.ts>

// 여기서 속성을 추가해주면 theme.ts에도 똑같이 작성해주어야 한다.
import "styled-components";

declare module "styled-components" {
  export interface DefaultTheme {
    bgColor: string;
    textColor: string;
    btnColor:string;
  }
}

 

 

실행결과

lightTheme

darkTheme

 

 

 

Comments