[React] Themes

hellow_coding·2023년 2월 4일

1. Create a declarations file

styled.d.ts

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

// and extend them!
declaremodule'styled-components'{   
  exportinterfaceDefaultTheme{   
    borderRadius:string; 

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

2. Create a theme

my-theme.ts

import{DefaultTheme}from'styled-components';     

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

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

export{ myTheme }; 

(1)

styled.d.ts

import "styled-components";

// 테마 정의를 확장
declare module "styled-components" {
  export interface DefaultTheme {
    textColor: string;
    bgColor: string;
    btnColor: string;
  }
}

(2) styled.d.ts 의 속성이 같게 입력

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)

App.tsx

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>Prorected</H1>
    </Container>

  );
}

export default App;

(4) ThemeProvider 은 theme을 필요로 한다.

index.tsx

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

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

참고 사이트

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

profile
꿈많은 개발자

0개의 댓글