Front-end/React

React + TS) Theme 세팅 ... Theme Provider

오열매 2023. 1. 16. 10:37

타입스크립트와 styled-components 테마를 연결

 

1) 설치: npm install @types/styled-components (이미 함)

 

2) declaration 파일 생성

... 기본적인 index.d.ts 파일은 있지만, 커스텀 파일을 만들어야 한다.

... src 폴더에 styled.d.ts 파일 생성 및 아래 코드 복붙

 

// [styled.d.ts]

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

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

    colors: {
      main: string;
      secondary: string;
    };
  }
}
// [theme.ts]

import { DefaultTheme } from 'styled-components';

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

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

export { myTheme };
// [index.tsx]

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

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <React.StrictMode>
    <ThemeProvider theme={myTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

 

ThemeProviderstyled-components로부터 오는 하나의 컴포넌트이다.

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

... ThemeProvider 컴포넌트 내부에 컴포넌트를 선언하면, 해당 내부 컴포넌트는

Theme Object에 접근할 수 있게 된다.