(CSS-in-JS) styled-components 사용방법, 요약정리


styled-components는 CSS 파일 없이도 JS 파일 내부에서 CSS를 작성할 수 있도록 도와주는 라이브러리이다.
프로젝트를 진행하면서 CSS와 JS파일을 왔다갔다하는 번거로움을 줄여준다고해서 사용해봤다.

styled-components를 사용해보면서 느낀 장점은 아래와 같다.

1. styled-components를 사용하면 한 창에서 디자인, 로직 모든것을 해결할 수 있다.

2. CSS 파일을 추가적으로 생성하지 않아도 된다.

3. SCSS 에서 사용하던 문법을 비슷하게 사용할 수 있다.

4. class 명칭을 고민하는 시간이 줄어든다.?



사용법과 간단하게 공부했던 내용을 정리해보려고 한다.

사용방법

import React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import "./MenuFont.css";

// styled-components
const List = styled.ul`
display: flex;
list-style: none;
`;

const Item = styled.li`
padding-right: 1rem;
`;

const StyledLink = styled(Link)`
text-decoration: none;
color: black;
`;

const CenterMenu = () => {
return (
<List className="Menu-Font">
<Item>
<StyledLink to="/">Home</StyledLink>
</Item>
<Item>
<StyledLink to="/about">About</StyledLink>
</Item>
</List>
);
};

export default CenterMenu;


const [변수명] = styled.[태그명]``;

바로 위의 문법으로 사용된다. 태그명 옆에 ``는 백틱이다.

// styled-components 라고 초록색 주석처리 된 밑에 코드를 보며 설명하면

ul 태그를 List 라는 명칭으로 사용한다고 생각하면 된다.

<ul className="Menu-Font">
<Item>
<StyledLink to="/">Home</StyledLink>
</Item>
<Item>
<StyledLink to="/about">About</StyledLink>
</Item>
</ul>

원래는 이렇게 되어있었다고 생각하면 된다.


Item도 스타일 컴포넌트가 적용된것이다. 

위에서 보면 li 태그를 Item 이라는 명칭으로 사용한다고 생각하면된다.

<ul className="Menu-Font">
<li>
<StyledLink to="/">Home</StyledLink>
</li>
<li>
<StyledLink to="/about">About</StyledLink>
</li>
</ul>


그렇고 해당 태그에 적용할 스타일들을 `` 백틱 사이에 작성하면된다.


단점은 자동완성이 안된다는건데 불편해서 찾아보니 역시나 나와 같이 불편을 느낀 분들이 미리 만들어놓은 extension이 존재했다.


설치하면 js파일안에서도 CSS 자동완성이 가능해진다.



몇가지 기능 요약 정리



1. 가상선택자 사용하는 방법 (&:hover)


// styled-components
const List = styled.ul`
display: flex;
list-style: none;
&:hover {
background: red;
}
&:focus {
background: green;
}
`;

& 특수 기호를 사용해서 가상 선택자를 선언해서 사용할 수 있다.


2. props 에 따른 스타일 속성 지정

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

const Button = styled.button`
font-size: 30px;
${(props) => {
if (props.success) {
return `background: green;`;
} else if (props.danger) {
return `background: red;`;
} else if (props.warning) {
return `background: yellow;`;
}
}}
`;

const Test = () => {
return (
<div>
<Button success>성공</Button>
<Button danger>위험</Button>
<Button warning>경고</Button>
</div>
);
};

export default Test;




props로 속성을 전달해서 조건에 따라 특정한 스타일을 지정할 수 있다.

이렇게 간단하게 상황에따라 CSS를 달리할 수 있다.


조건이 두개라면 아래와 같이 삼항연산자로 간단하게 작성하는것도 가능하다.

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

const Button = styled.button`
font-size: 30px;
background: ${(props) => (props.success ? "green" : "red")};
`;

const Test = () => {
return (
<div>
<Button success>성공</Button>
<Button danger>위험</Button>
</div>
);
};

export default Test;



3. Global 속성 지정하기 (createGlobalStyle)

프로젝트를 시작할때 CSS 기본설정으로 

* {
padding: 0;
margin: 0;
box-sizing: border-box;
/* 추가적으로 font 설정 */
}

아래와 같이 작성하고 시작한다. 이렇게 해야지 CSS를 적용하기 편해지는데 

styled-components에서도 간단하게 적용가능하다.

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
* {
box-sizing: border-box;
padding:0;
margin:0;
}
`;

createGlobalStyle을 import 하여 위에서 처럼 선언하여 사용가능하다.

React의 경우 보통 App.js에 작성한다. 그러면 App.js안에 작성된 모든 컴포넌트들에게 적용된다.

적용하는방법은 굳이 태그를 만들어서 감쌀 필요없이

<GlobalStyle />

컴포넌트들이 모여있는곳 맨 상단에 작성해주면 속성이 global로 적용된다.




4. 태그안에 속성 지정하기 (.attrs)

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

const Input = styled.input.attrs({
placeholder: "이름을 입력하세요.",
required: true,
})`
background: green;
`;

const Test = () => {
return (
<div>
<Input type="text" />
</div>
);
};

export default Test;


.attrs API를 사용하여 태그안에 속성을 지정할 수 있다.


.attrs 적용 후 출력 결과




5. Mixin(믹스인) 사용하기 (CSS 블럭 재활용하기)

import styled, { css } from "styled-components";

const testMixin = css`
font-size: 14px;
background: blue;
`;

Mixin(믹스인) 기능을 사용하기 위해서는 css 를 styled-components로부터 import 해와야 한다.

적용은 아래와 같이 가능하다.

import React from "react";
import styled, { css } from "styled-components";

const testMixin = css`
font-size: 14px;
background: blue;
`;

const Input = styled.input.attrs({
placeholder: "이름을 입력하세요.",
required: true,
})`
color: green;
${testMixin}
`;

const Test = () => {
return (
<div>
<Input type="text" />
</div>
);
};

export default Test;



${믹스인변수} 를 작성해주면 적용된다. 공통적으로 많이 사용되는 속성들을 Mixin에다가 적어두어 작성하면 코드의 중복을 막을 수 있다.



6. 공통속성 사용하기 (ThemeProvider)   ex)Dark Mode

App.js
import React from "react";
//ThemeProvider 불러오기
import { ThemeProvider } from "styled-components";
//공통속성 작성한 js파일 불러오기
import theme from "./components/theme";
// 적용할 컴포넌트들
import Button1 from "./components/Button1";
import Button2 from "./components/Button2";
import Button3 from "./components/Button3";

const App = () => {
return (
<ThemeProvider theme={theme}>
<Button1 />
<Button2 />
<Button3 />
</ThemeProvider>
);
};

export default App;


theme.js
const theme = {
mainColor: "#e9ebdd",
danderColor: "#c91478",
successColor: "#44944d",
dayMode: "#e99999",
nightMode: "#5c5645",
};

export default theme;


Button1.js
import React from "react";
import styled from "styled-components";

const Butto = styled.button`
background: ${(props) => props.theme.successColor};
`;

const Button1 = () => {
return (
<div>
<Butto>버튼</Butto>
</div>
);
};

export default Button1;



ThemeProvider를 styled-components로부터 불러오고, 공통으로 사용될 생상들을 theme.js에 작성하고 export default 한다.

적용방법은 위에서와 같이 ThemeProvider로 모든 컴포넌트를 감싸고 theme의 props값으로 theme.js에서 import 해온 theme을 넘겨준다. 

그러면 ThemeProvider의 하위 컴포넌트 모든곳에서 props를 통해서 theme에 작성한 색상을 적용할 수 있다.

Button1.js 에서와 같이 props => props.theme.successColor 를 적용해면 theme.js 에서 선언한 successColor 해당 속성이 적용된다.

최상위 컴포넌트인 App 컴포넌트에 적용하여 다크 모드(Dark Mode) 적용에 사용하면 좋다.




7. 상속하기 (.withComponent)

import React from "react";
//ThemeProvider 불러오기
import styled, { ThemeProvider } from "styled-components";
//공통속성 작성한 js파일 불러오기
import theme from "./components/theme";
const Button = styled.button`
background: yellow;
`;

const Link = styled(Button.withComponent("a"))`
color: red;
`;

const App = () => {
return (
<ThemeProvider theme={theme}>
<Button>버튼1</Button>
<Button>버튼2</Button>
<Button>버튼3</Button>
<Link>속성 상속 받기</Link>
</ThemeProvider>
);
};

export default App;




styled-components에서 상속을 받을때는 extend가 아닌 withComponent API를 사용한다.

Button에 작성한 CSS를 Link라는 a 태그에 적용한것이다.

사용법은 styled(Button.withComponent('a'))`` 와 같이 작성한다.




8. SCSS 처럼 Nesting 사용하기 (${하위컴포넌트}{CSS속성})


SCSS 에서는 CSS처럼  header form input {} 이렇게 작성하지 않고 아래와 같이 직관적으로 Nesting한 태그들을 작성하여 SCSS 코드들을 작성할 수 있었다.

header {
    h1{

    }
    form{
          
        input {

        }
    }    
}


styled-components 에서도 역시 Nesting 하게 작성할 수 있다.

import React from "react";
//ThemeProvider 불러오기
import styled, { ThemeProvider } from "styled-components";
//공통속성 작성한 js파일 불러오기
import theme from "./components/theme";
// 하위 컴포넌트들
import Button1 from "./components/Button1";
const Form = styled.form`
background: black;
${Button1} {
background: purple;
}
`;

const App = () => {
return (
<ThemeProvider theme={theme}>
<Form>
<Button1 />
</Form>
</ThemeProvider>
);
};

export default App;



상위 컴포넌트에서 하위 컴포넌트인 Button1에 CSS 스타일링을  ${하위컴포넌트명}{CSS속성} 와 같은 문법으로 Nesting하게 작성할 수 있다.







styled-components 공식 홈페이지

댓글