Language/Typescript

[Typescript] styled Components Typescript Definitions

khakhalog 2023. 1. 7. 23:29

https://styled-components.com/docs/api#typescript

 

styled-components: API Reference

API Reference of styled-components

styled-components.com

 

1. Create a declarations file

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;
    };
  }
}

 

2. Create a theme

defaultTheme을 사용하여 theme을 만들어준다.

 

Theme.ts

import { DefaultTheme } from "styled-components";

export const lightTheme: DefaultTheme = {
  bgColor: "white",
  textColor: "black",
  btnColor: "tomato",
};

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

 

3. Styling Components

theme을 사용할 컴포넌트에서 구성할 styledcomponents에서 props로 넘겨받은 theme안의 스타일을 지정해준다.

이때, index.tsx에서는 ThemeProvider를 import하여 다음과 같이 theme을 넘겨줘야한다.

 

index.tsx

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

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

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

 

App.tsx

import React, { useState } from "react";
import styled from "styled-components";

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

const H1 = styled.h1`
  color: ${(props) => props.theme.textColor};
`;

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