[styled-components] theme에 반응형 기준사이즈 및 자주쓰는 컬러 추가하기

2023. 3. 7. 19:27
반응형

App/Index.tsx 파일 등이 themeProvider로 감싸져있는 상태에서 시작

// App.index

import { theme } from 'src/styles/theme';

...

<ThemeProvider theme={theme}>
  <GlobalStyle />
  <App />
</ThemeProvider>

 

 

자주쓰는 컬러 팔레트 만들기

1) theme.ts 파일에 원하는 색상값 설정 

// theme.ts

const myColor = {
  main: '#546de5',
  light: '#778beb',
  deep: '#3146ad',
};

export const theme = {
  myColor,
};

export type Theme = typeof theme;

 

2) styled.d.ts 파일에 인터페이스 설정

(타입스크립트 사용을 위함! styled.d.ts 파일 위치는 자신이 편한 곳에다 만들기)

import { Theme } from 'src/styles/theme';
import { CSSProp } from 'styled-components';

declare module 'styled-components' {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  export interface DefaultTheme extends Theme {}
}

자동완성되어 편하게 쓸 수 있다

 

 

 

반응형 기준 사이즈 설정하기

 

방법 1) theme.ts 파일에 아래 부분 추가

const media = {
  mobile: '(max-width: 500px)',
  labtop: '(min-width: 501px) and (max-width: 1300px)',
}

...

export const theme = {
  myColor,
  media, //위에 새로 작성한 media가 추가됨
};

 

사용하기

 

 

 


 

 

방법 2) theme.ts 파일에 아래 부분 추가

// theme.ts

type MediaQueryProps = {
  mobile: number;
  labtop: number;
};

const sizes: MediaQueryProps = {
  mobile: 500,
  labtop: 1280,
};

// Iterate through the sizes and create a media template
type BackQuoteArgs = string[];

const media = {
  mobile: (literals: TemplateStringsArray, ...args: BackQuoteArgs): CSSProp =>
    css`
      @media only screen and (max-width: ${sizes.mobile}px) {
        ${css(literals, ...args)}
      }
    `,
  labtop: (literals: TemplateStringsArray, ...args: BackQuoteArgs): CSSProp =>
    css`
      @media only screen and (max-width: ${sizes.labtop}px) {
        ${css(literals, ...args)}
      }
    `,
} as Record<
  keyof typeof sizes,
  (l: TemplateStringsArray, ...p: BackQuoteArgs) => CSSProp
>;

...


export const theme = {
  myColor,
  media, //위에 새로 작성한 media가 추가됨
};

 

사용하기

 

 

 

 

 

 

참고문서

https://flamingotiger.github.io/style/styled-components-typescript/

https://www.daleseo.com/css-media-queries/

반응형

BELATED ARTICLES

more