React

TIL | React + twin.macro(with styled-component) 세팅

Twin?

  • tailwindcss-in-js를 혼용을 가능케 하는 css 라이브러리

 

Setting

Install

npm install twin.macro tailwindcss styled-components
# or 
yarn add twin.macro tailwindcss styled-components
# 추가적으로 @emotion/styled @emotion/react도 설치가 필요하다.
yarn add @emotion/styled @emotion/react

 

GlobalStyles 설정

import { createGlobalStyle } from "styled-components";
import tw, { GlobalStyles as BaseStyles } from "twin.macro";

const CustomGlobalStyles = createGlobalStyle`
  // custom styling
`;

const GlobalStyles = () => {
  return (
    <>
      <BaseStyles />
      <CustomGlobalStyles />
    </>
  );
};

export default GlobalStyles;

 

GlobalStyle import

import React from "react";
import ReactDOM from "react-dom/client";
import { Router } from "./routes/Router";
import GlobalStyles from "./styles/GlobalStyles";

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <React.StrictMode>
    <GlobalStyles />
    <Router />
  </React.StrictMode>
);

 

사용법

const StyledWrapper = styled.button`
  ${tw`px-4 py-2 border-2 letter-spacing[2px] relative border-transparent duration-300
    hover:(text-white)
    active:scale-[0.99]
  `}

  span {
    transition:transform 300ms;
    }
  `
  • 위 예시와 같이 tailwindcss 문법과 css-in-js를 혼용하여 위와 같이 사용할 수 있다. 자세한 사용 방법은 공식문서에 잘 나와있으니 참고하도록 하자.

 

Reference