React component를 styled-components로 다시 구현하는 중에 이상한 점이 있었다.
아래와 같은 Section component가 있다. 이 component는 화면의 section 영역을 구분할 때 사용하고, spacing prop을 사용해서 flexbox의 gap을 설정한다.
export default function Section({ spacing = 16, children }) {
return (
<section
className="ItemsSection"
style={{
width: "100%",
display: "flex",
flexDirection: "column",
gap: spacing
}}
>
{children}
</section>
);
}
이 component를 styled-components를 사용해서 아래와 같이 변경하였다.
import styled from "styled-components";
const StyledSection = styled.section`
width: 100%;
display: flex;
flex-direction: column;
gap: ${({ spacing }) => spacing}px;
`;
export default function Section({ spacing = 16, children }) {
return <StyledSection spacing={spacing}>{children}</StyledSection>
}
이 코드에서 spacing이라는 속성은 section tag로 그대로 전달된다. 그런데, 비표준 속성을 HTML tag로 전달할 때 warning 또는 error가 발생할 수 있으므로 transient prop($spacing)을 사용하는 것이 권장된다. styled-components는 이런 상황에서 transient prop을 자동으로 filtering해서 HTML tag에 전달되지 않도록 처리한다.
import styled from "styled-components";
const StyledSection = styled.section`
width: 100%;
display: flex;
flex-direction: column;
gap: ${({ $spacing }) => $spacing}px;
`;
export default function Section({ spacing = 16, children }) {
return <StyledSection $spacing={spacing}>{children}</StyledSection>
}
그런데, spacing을 transient prop으로 사용했을 때는 왜 warning이나 error가 발생하지 않을까? spacing이 아니라 underline 같은 다른 임의의 속성을 사용할 때는 정상적으로 warning이 발생하는 것과 대조적이다.
(말이 안되긴 하지만) 아래와 같이 underline을 사용하면 console에 warning이 출력된다.
...
export default function Section({ spacing = 16, children }) {
return (
<StyledSection $spacing={spacing} underline="hello">
{children}
</StyledSection>
);
}

underline을 transient prop으로 사용하면 warning이 사라진다.
...
export default function Section({ spacing = 16, children }) {
return (
<StyledSection $spacing={spacing} $underline="hello">
{children}
</StyledSection>
);
}
styled-components가 component의 prop을 처리하는 방식Warning message를 보면 맨 앞이 "styled-components:"로 시작한다. 즉, 이 warning은 styled-components package가 발생시키는 것이다.