반응형
Styled Component란?
CSS-in-JS라고 하는 JavaScript 파일 안에서 CSS를 처리할 수 있게 해주는 라이브러리다. 클래스 네임을 중복해서 사용시 생기는 버그를 방지하고, 구조적으로 컴포넌트와 스타일이 묶여있어 유지보수를 용이하게 한다.
사용법
설치
$ npm install --save styled-components
기본 문법
import React from 'react'
import styled from 'styled-components'
// create styled-component
const Container = styled.div`
color: white;
background: black;
`
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
const Sample = () => {
return (
<Container>
<Title>
h1 타이틀
</Title>
</Container>
)
}
export default Sample
Nesting 구조
SCSS처럼 Nesting 구조(& 사용)를 지원한다.
const Nesting = styled.div`
color: blue;
&:hover {
color: red;
}
#id {
div {}
background: orange;
}
.something-else & {
border: 1px solid;
}
`
Extending Styles (스타일 상속)
render(
<div>
<Button>Normal Button</Button>
<RedButton>Red Button</TomatoButton>
</div>
);
// 기본 버튼 스타일
const Button = styled.button`
color: gray;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
`;
// 기본 버튼 스타일을 상속한 스타일
const RedButton = styled(Button)`
color: Red;
border-color: Red;
`;
Global Styles (전역 스타일)
전역 스타일을 지정할 수 있다. index.js에만 import 하면 모든 페이지와 컴포넌트에서 특정 스타일을 전역으로 불러온다.
// index.js
import StyleTheme from "./Styles/StyleTheme";
import StyleGlobal from "./Styles/StyleGlobal";
// 각 컴포넌트에서 아래와 같이 사용하면 된다.
color: ${(props) => props.theme.colors.redColor};
state에 따른 style 지정
visibility: ${(props) => (props.unVisibility ? "hidden" : "visible")};
공식 문서
https://styled-components.com/
styled-components
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅🏾
styled-components.com
반응형
'웹_프론트엔드 > 로드맵 챌린지' 카테고리의 다른 글
Modern CSS - Styled JSX (0) | 2022.02.23 |
---|---|
Modern CSS - CSS Modules (0) | 2022.02.22 |
상태 관리 라이브러리 - Vuex (0) | 2022.02.17 |
프레임워크 - Vue.js (0) | 2022.02.16 |
상태 관리 프레임워크 - NgRx란? (0) | 2022.02.15 |