TypeScript+Styeld-Component+Theme

sonnng·2023년 1월 3일
0

React

목록 보기
5/8

styled-component에 원하는 인터페이스를 추가해 styled-component에 활용하고자 하는 경우

1. 파일생성

(1) .d.ts ->styled-component 문서참고하여 d.ts 파일 생성

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

// and extend them!
declare module "styled-components" {
  export interface DefaultTheme {
    bgColor: string;
    textColor: string;
  }
}

(2) .ts -> 위 링크따라 참고하여 .ts 파일 생성(원하는 theme object 작성)

import { DefaultTheme } from "styled-components";

export const lightTheme: DefaultTheme = {
  bgColor: "smokeWhite",
  textColor: "#111",
};
export const darkTheme: DefaultTheme = {
  bgColor: "#111",
  textColor: "white",
};

2. theme object 활용

(1) index.tsx -> ThemeProvider import, theme props로 theme object 불러온다.
(2) App.tsx 포함 하위 컴포넌트들 -> theme object의 props 사용

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>Unigram</H1>
    </Container>
  );
}

export default App;

0개의 댓글