&&
은 특정 컴포넌트의 인스턴스를 참조할 수 있다!
&
을 기존의 포스팅에서 설명했듯이, className을 참조한다는 것이다. 그러면 &&
은 결국은 .className.className
이 될 것이다. CSS에서 이것은 두 개 이상의 선택자를 결합하는 데 사용될 것이며, 특정성을 높여줄것이다! 즉, &&
을 사용하면 특정 컴포넌트의 인스턴스에 대해서만 스타일을 적용할 수 있고, 조건부 스타일링에 유용하다! 일관성을 유지? 하기에도 편하다고 한단다. 흠,,
예시를 보도록하자!
const Input = styled.input.attrs({ type: "checkbox" })``;
const Label = styled.label`
align-items: center;
display: flex;
gap: 8px;
margin-bottom: 8px;
`;
간단하게 Input
을 만드는데, checkbox
로 하고 싶으니깐 attrs
로 checkbox attributes를 넘겨줬다.
Label
은 cross-axis를 가운데에 맞추고, flex, 간격 8px, 아래 margin 8px 낮추었다.
이제 &&
연산을 어떻게 사용하는지 보도록 하자!
const LabelText = styled.span`
${(props) => {
switch (props.mode) {
case "dark":
return `
background-color: black;
color: white;
${Input}:checked + && {
color: blue;
}
`;
default:
return `
background-color: white;
color: black;
${Input}:checked + && {
color: red;
}
`;
}
}}
`;
LabelText
는 span
태그로 만들어져 있고, props인 mode
에 따라 스타일이 변한다! switch 구문만 따로 빼서 보면, mode === dark 일 때, case "dark"가 될 것이다.
${(props) => {
switch (props.mode) {
case "dark":
return null
default
return null
}
}}
물론 다음과 같이 쓸 수도 있을 것이다.
${(props) => {
props.mode === "dark" ? /* dark style */ : /* default style */
}}
편한거 쓰쇼. 각자의 장점이 있을거라 믿는다!
그리고 가장 난해한 구문을 보도록 하자.
case "dark":
return `
background-color: black;
color: white;
${Input}:checked + && {
color: blue;
`;
Input
컴포넌트에 :checked
Psuedo Elements를 적용하고, LabelText
내부의 span
를 참조하기 위한 것이다! 여기서 &
하나 만 쓰면 적용이 안되는 것을 확인 할 수 있다,,,
더 설명하자면,
&&
은 styled-components와 vanilla CSS 에서 충돌하는 스타일에서 "precedence boost"라는 특별한 동작을 가지고 우선순위를 높이는데 유용할 수 있단다!
예시코드
const Thing = styled.div`
&& {
color: blue;
}
`
const GlobalStyle = createGlobalStyle`
div${Thing} {
color: red;
}
`
render(
<React.Fragment>
<GlobalStyle />
<Thing>
I'm blue, da ba dee da ba daa
</Thing>
</React.Fragment>
)
이처럼 globalStyle로 div${Thing}이 red가 되야하지만, &&
로 blue가 된 것을 볼 수 있다!
다음 포스팅은 attaching additional props, Overriding attrs 와 Animation을 알아보고 styled-components의 기본을 끝낸 기념으로 클론하나 하겠다!