Styled-component란?
Javascript 파일 내에서 CSS를 사용할 수 있게 해주는 대표적인 CSS-in-JS 라이브러리로 React 프레임워크를 주요 대상으로 한 라이브러리다.
yarn add styled-component
// styled-components 라이브러리에서 import 해온 styled라는 객체를 이용한다
// 아래와 같이 h1태그를 만들어 Title이라는 styled 컴포넌트를 만들 수 있다
import styled from 'styled-componets'
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
const 위에서 지정한 component 명 = styled.태그명 ``
styled.태그명 ``; 부분에 해당
const Button = styled.button`
/* Adapt the colors based on primary prop */
background: ${props => props.width < 200 ? "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 width="100">Primary</Button>
</div>
);
<TagBox className={isHidden ? "hidden" : "visible"}>
----- ----- ----- ----- ----- ----- ----- -----
.hidden {
visibility: hidden;
}
.visible {
visibility: visible;
}
<TagBox unVisibility={isHidden}>
----- ----- ----- ----- ----- ----- ----- -----
visibility: ${(props) => (props.unVisibility ? "hidden" : "visible")};
→ 이렇게 useState로 관리되는 상태 값을 props로 넘겨줄 수 있다
// 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>
);
→ TomatoButton은 기존의 스타일링된 Button을 extend해서 사용할 수 있다.
// This could be react-router-dom's Link for example
const Link = ({ className, children }) => (
<a className={className}>
{children}
</a>
);
const StyledLink = styled(Link)`
color: palevioletred;
font-weight: bold;
`;
render(
<div>
<Link>Unstyled, boring Link</Link>
<br />
<StyledLink>Styled, exciting Link</StyledLink>
</div>
);