말 그대로 스타일을 가진 컴포넌트라는 뜻으로 기존의 css,scss와는 다르게 동적인 스타일링을 할 수 있고 클래스네임을 사용하지 않고 다른 클래스네임으로 변경해주기 때문에 서로 겹치는 경우가 발생하지 않고 좀 더 동적이 스타일링을 할 수 있다. 그 외 자세한 내용은 해당 공식 문서를 참고하면 좋을거 같다.
npm install --save styled-components
import styled from "styled-components";
=> 사용하고자 하는 컴포넌트에 임포트 한다.
const "컴포넌트명" = styled."HTML element"`` => 이러한 형태로 컴포넌트를 스타일링 하고 백틱 안에 기존 CSS 문법으로 사용하면 된다.
props로 전달
import React, { Component, Fragment } from 'react';
import styled from 'styled-components';
class App extends Component {
render() {
return (
<Fragment>
<Button>Hello</Button>
<Button danger>Hello</Button>
</Fragment>
)
}
}
const Button = styled.button`
border-radius: 50px;
padding: 5px;
min-width: 120px;
color: white;
font-weight: 600;
-webkit-appearance: none;
cursor: pointer;
&:active,
&:focus {
outline: none;
}
background-color: ${props => (props.danger ? 'red' : 'purple')}
`;
export default App;
위와 같이 스타일컴포넌트에 props를 할당하여 스타일에 background-color에 적용한 모습을 볼 수 있다.
render(
<>
<Thing>Hello world!</Thing>
<Thing>How ya doing?</Thing>
<Thing className="something">The sun is shining...</Thing>
<div>Pretty nice day today.</div>
<Thing>Don't you think?</Thing>
<div className="something-else">
<Thing>Splendid.</Thing>
</div>
</>
)
const Thing = styled.div`
color: blue;
&:hover {
color: red;
}
#id {
div {
background: orange;
}
}
.something-else & {
border: 1px solid;
}