styled-components 사용해 보기

chaticker·2022년 4월 6일
0

CSS

목록 보기
1/1
post-thumbnail

styled-components?

javascript에서 css를 사용 할 수 있도록 도와주는 스타일링 프레임워크

✅ Component 단위로 스타일링 가능: 클래스명 중복 방지
✅ 조건부 스타일링: 컴포넌트의 props를 전달받아 사용 가능
✅ 확장 스타일링: 새로운 Component를 선언하는 것 뿐만 아니라, 기존의 Component에 스타일을 추가하는 것도 가능
✅ SASS의 중첩 스코프 규칙 사용 가능(모든 규칙 사용은 아님)


🟢 babel 설정

npm i -D @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript

🔵 styled-components 설치

npm i styled-components

🟣 .babelrc.js 생성 및 설정

module.exports = () => {
  return {
    presets: [
      "@babel/preset-env",
      "@babel/preset-typescript",
      "@babel/preset-react",
    ],
    plugins: [
      ["@babel/plugin-proposal-class-properties"],
      ["styled-components", { ssr: true }], //추가
    ],
  };
};

🟡 사용해 보기 👇🏻

> 기본

/* /src/App.tsx */

import * as React from "react";
import styled from "styled-components";

function App() {
  const Title = styled.h1`
    font-size: 1.5em;
    text-align: center;
    color: palevioletred;
  `;
  return (
    <div>
      <Title>chaticker</Title>
    </div>
  );
}

export default App;

> 조건부 스타일링 - props

import * as React from "react";
import styled from "styled-components";

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  background: ${(props) => (props.color ? props.color : "red")};
`;

function App() {
  return (
    <div>
      <Title>chaticker</Title>
      /* props 전달 */
      <Title color="blue">chaticker</Title>
    </div>
  );
}

export default App;

> 확장 스타일링

import * as React from "react";
import styled from "styled-components";

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  background: ${(props) => (props.color ? props.color : "red")};
`;

/* 기존 Title 스타일에 새로운 스타일 추가 */
const BlackTitle = styled(Title)`
  background: black;
  color: white;
`;

function App() {
  return (
    <div>
      <Title>chaticker</Title>
      <Title color="blue">chaticker</Title>
      <BlackTitle>chaticker</BlackTitle>
    </div>
  );
}

export default App;

> 중첩 스코프

import * as React from "react";
import styled from "styled-components";

const BlackTitle = styled(Title)`
  background: black;
  color: white;
  p {
    color: red;
  }
`;

function App() {
  return (
    <div>
      <BlackTitle>
        chaticker
        <p>hi</p>
      </BlackTitle>
    </div>
  );
}

export default App;

참고

profile
개발계발

0개의 댓글