민프

[React][TypeScript] React + TypeScript + styled Component + Theme을 적용해보자 본문

[React]

[React][TypeScript] React + TypeScript + styled Component + Theme을 적용해보자

민프야 2023. 1. 25. 11:31

이번 포스팅에서는 공식문서를 참고하여 typeScript에서 styled Component를 이용해서 theme을 적용해보는 부분을 해보려고 한다. 

 

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

 

styled-components: API Reference

API Reference of styled-components

styled-components.com

 

1. npm 설치해주기

# Web
npm install --save-dev @types/styled-components

# React Native
npm install --save-dev @types/styled-components @types/styled-components-react-native

2. src에 declarations file 만들어주기 (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;
    };
  }
}

이 파일은 우리가 이전에 설치해 놓은 styled-components/index.d.ts 파일을 override할 것이다.

 

3. src에 theme.js 만들기

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

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

4. index.tsx에 "ThemeProvider" 만들어주기

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



ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={lightTheme}>
      <App />
      </ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals

5. App.js에 적용하기

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

function App() {

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

  return (
    <Container>
      <H1>protected</H1>
    </Container>

  );
}

export default App;

 

 

Comments