[React] styled-components

AI 개발자 웅이·2022년 6월 8일
0

React

목록 보기
6/9

styled-components는 기존에 css, scss 파일을 밖에 두고 태그나 id, class이름으로 가져와 쓰는 스타일 지정 방식에서 벗어나, js 파일 내에서 컴포넌트 이름을 쓰듯 스타일을 지정하는 react 라이브러리다. css 파일을 따로 만드는 번거러움을 없앴고, 컴포넌트만 입력하면 class name을 자동으로 부여하기 때문에 css가 전역으로 중첩되지 않도록 만들어주는 장점이 있다.

styled-components는 npm 명령어로 설치할 수 있다.

npm i styled-components
  • vscode-styled-components extension을 다운받으면 styled-components 자동완성 기능을 사용할 수 있다.

styled-components 기본 문법

  1. 우선, styled-components에서 styled를 import해준다.
import styled from "styled-components";
  1. 스타일을 지정하는 컴포넌트를 생성하고 그것을 태그 형식으로 사용할 수 있다.

example)

const Box = styled.div`
  background-color: tomato;
  width: 100px;
  height: 100px;
`;

function App() {
return (
  <Box>
    <span>Hello</span>
  </Box>
 )}
  1. 부모 스타일을 상속받을 수 있고 props 또한 지정할 수 있다.
    example)
const Circle = styled(Box)`
  border-radius: 50px;
  background-color: ${(props) => props.bgColor};
`;

function App() {
return (
  <Circle bgColor="whitesmoke">
    <span>Hello</span>
  </Circle>
 )}
  1. .attrs를 이용하여 base 태그의 props를 지정할 수 있다.
const Input = styled.input.attrs({ required: true, maxLength: 10 })`
  background-color: tomato;
`;
  1. as props를 사용하여 같은 스타일의 다른 태그로 변경 가능하다.
  <Box as="main">
    <span>Hello</span>
  </Box>
  1. keyframes을 이용하여 애니메이션을 생성할 수 있다.
import {keyframes} from "styled-components";

const animation = keyframes`
0% {
  transform: rotateZ(0deg);
  border-radius: 0px;
}
50% {
  transform: rotateZ(180deg);
  border-radius: 25px;
}

100% {
  transform: rotateZ(360deg);
  border-radius: 50px;
}
`;

const Box = styled.div`
  width: 100px;
  height: 100px;
  animation: ${animation} 1s linear infinite;
`;

모든 style component들은 export하여 다른 파일에서 재사용 가능하다.

styled-components theme 설정

  1. 우선, styled-components에서 ThemeProvider를 import해준다.
import { ThemeProvider } from "styled-components";
  1. theme 컴포넌트를 설정하고 ThemeProvider의 theme props 값으로 받아준다.
const darkTheme = {
  textColor: "whitesmoke",
  backgroundColor: "black",
};

const lightTheme = {
  textColor: "black",
  backgroundColor: "whitesmoke",
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <ThemeProvider theme={darkTheme}>
    <App />
  </ThemeProvider>
);
  1. 전역에서 theme 스타일을 사용할 수 있으며, theme으로 지정한 컴포넌트에 따라 모든 스타일이 바뀌도록 설정할 수 있다.
const Circle = styled(Box)`
  border-radius: 50px;
  background-color: ${(props) => props.theme.backgroundColor};
`;
  1. typescript로 theme을 설정하기 위해서는 styled.d.ts 파일이 필요하다.

styled.d.ts

import "styled-components";

declare module "styled-components" {
  export interface DefaultTheme {
    red: string;
    black: {
      veryDark: string;
      darker: string;
      lighter: string;
    };
    white: {
      darker: string;
      lighter: string;
    };
  }
}

theme.ts

import { DefaultTheme } from "styled-components";

export const theme: DefaultTheme = {
  red: "#E51013",
  black: {
    veryDark: "#141414",
    darker: "#181818",
    lighter: "#2F2F2F",
  },
  white: {
    lighter: "#fff",
    darker: "#e5e5e5",
  },
};
profile
저는 AI 개발자 '웅'입니다. AI 연구 및 개발 관련 잡다한 내용을 다룹니다 :)

0개의 댓글