Styled-component

이진경·2023년 1월 18일
0
post-thumbnail

✅ Styled-component

Styled-component란 기존 돔을 만드는 방식인 css, scss 파일을 밖에 두고 태그나 id, class 이름으로 가져와 쓰지 않고, 컴포넌트 이름을 쓰듯 스타일을 지정하는 것이다.
css 파일을 밖에 두지 않고, 컴포넌트 내부에 넣기 때문에 css가 전역으로 중첩되지 않도록 만들어주는 장점이 있다.

⚙️ 설치방법

npm i styled-components

위 명령어를 사용해 styled-component를 설치한다.

import styled from 'styled-components'

styled-component를 사용할 곳에 import해준다.

✍️ 사용방법

const Box = styled.div`
  background: #ddd;
  padding: 20px;
`;
const YelloBtn = styled.button`
  background: ${(props) => props.bg};
  color: ${(props) => props.bg == "blue" ? "white" : '#000'};
  padding: 10px;
`;
const NewBtn = styled.button(YelloBtn);

<Box>
  	<YelloBtn bg="blue">버튼</YelloBtn>
	<YelloBtn bg="orange">버튼</YelloBtn>
</Box>
  • const 로 변수를 선언해주고 styled.태그명을 지정 후 백틱기호를 사용해서 css 속성을 입력해준다.
  • 하나의 styled-component를 만들고 한개의 속성만을 변경하고 싶다면 props 문법으로 변경 가능하다.

👉 global Theme

전역으로도 css를 정의할 수있다.

//theme.js

const theme = {
  successColor : white;
  dangerColor : red;
}

export default theme
  1. root 레벨에 공동으로 사용할 theme.js를 만든다.
import React, { Component } from "react";
import styled, { ThemeProvider } from "styled-components";
import theme from "./theme";

class App extends Component {
  render() {
    return (
      <ThemeProvider theme={theme}>
        <Container>...</Container>
      </ThemeProvider>
    );
  }
}
  1. ThemePrivider를 프로젝트의 root dir에 import하고 아래처럼 선언하여 사용한다.

✍️ 장점

  1. css 파일없이 js 파일에서 바로 스타일을 지정할 수 있다.
  2. html <style>태그에 넣어주기 때문에 페이지 로딩 시간이 단축된다.
  3. 변수에 의해 style을 변경할 수 있고, 내부적으로 props을 받을 수 있다.

✍️ 단점

  1. js파일이 복잡해지고 일반 컴포넌트인지 styled 컴포넌트인지 헷갈린다.
  2. js파일 간 중복 스타일이 많아지면 그냥 css 파일 import 하는 것과 큰 차이가 없다.
profile
멋찐 프론트엔드 개발자가 되자!

0개의 댓글