이번 프로젝트를 진행하며 style-components
를 활용하여 css를 구성해보자는 이야기가 나왔다.
그렇다면 style-components
는 무엇일까?
styled-componets 공식문서
styled-components
는CSS
를component
에 사용 할 수 있게 한다
mapping
을style
ㅈ과component
로 부터 제거함으로component
를 low-level styling 으로 구성하여 쉽게 사용 할 수 있게 도와준다
style-componets
는 React
컴포넌트를 설계하는데 있어 CSS styling을 enhance하는데서 나왔다.
제공하는 기능은 다음과 같다.
style-components
는 스타일에 대한 고유한 클래스 이름을 생성한다. 중복 혹은 철자 오류에 대해 걱정할 필요없다.style-components
는 분명히 한다. 구성 요소가 사용되지 않고 삭제되면 해당 구성 요소의 모든 스타일도 함께 삭제된다.props
혹은 전역
을 기반으로 구성 요소의 스타일을 적용하는 것이 간단하고 직관적이다.style-components
가 처리하도록 한다.// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
// Use Title and Wrapper like any other React component – except they're styled!
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
JavaScript
혹은 React.js
를 공부하였다면, 다음과 같은 예시 코드를 통해 쉽게 작동 방식을 알 수 있었다.
위의 변수 선언(Title, Wrapper)은 styled의 section과 h1의 tag
속성을 지닌 객체 선언처럼 보이며,
아래의 render 과정에서 선언된 변수는 tag
로 사용됨을 알 수 있다.
const Button = styled.button`
/* Adapt the colors based on primary prop */
background: ${props => props.primary ? "palevioletred" : "white"};
color: ${props => props.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
render(
<div>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
위의 코드를 통해 styled-component에서 CSS
조건부 스타일링을 선언식 안에서 적용 할 수 있다는 것을 확인 할 수 있다.
// The Button from the last section without the interpolations
const Button = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
color: tomato;
border-color: tomato;
`;
render(
<div>
<Button>Normal Button</Button>
<TomatoButton>Tomato Button</TomatoButton>
</div>
);
위의 코드는 Button의 속성에서 반복적인 부분 중 일부의 Button에 대해 추가/변경 하고 싶을 때 사용되는 방식이다. styled()
생성자로 앞선 styled-component를 상속받을 수 있다.
더 많은 정보는 공식문서를 통해 확인 할 수 있다.
또한 Tagged Template Literal
를 이해 한다면, 더욱 styled-component
를 이해하는데 도움이 될 것이다.