토이프로젝트2가 시작되면서 styled components를 사용하게 되었다.
사용하면서 몇몇 오류가 발생했고, 대부분의 오류가 styled components에 대해 잘 모르고 사용해서 생긴 오류라는 걸 알게되었다.
기억에 남는 상황을 몇가지 기록해보고자 한다.
const StyledButton = styled.button`
/* ...some styles */
${({ fullWidth }) => (fullWidth ? '100%' : 'auto')};
`
export default function Button({
children,
disabled = false,
fullWidth = false,
onClick,
...props
}) {
return (
<S.Button
fullWidth={fullWidth}
disabled={disabled}
onClick={onClick}
{...props}
>
{children}
</S.Button>
)
}
위 코드를 보면 fullWidth라는 prop을 받아서 버튼 너비를 결정하고 있다.
하지만 위처럼 작성하고 확인해보니 다음과 같은 오류가 발생했고, 해당 오류는 HTML DOM 요소가 인식못하는 prop를 전달했기 때문에 발생하는 것이라고 한다.
Warning: React does not recognize the
fullWidthprop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercasefullwidthinstead. If you accidentally passed it from a parent component, remove it from the DOM element. Error Component Stack
styled-components가 DOM을 생성할때 커스텀한 props를 어떻게 구분하는가를 조금만 생각해봤다면 위와 같은 코드를 작성할때 애초에 의문을 가질 수 있지 않았을까..
해결방법은 간단했다. styled-components는 커스텀 props를 접두어로 $가 붙었느냐 아니냐로 구분한다.
따라서 다음과 같이 수정하면 정상적으로 잘 동작한다.
const StyledButton = styled.button`
/* ...some styles */
${({ $fullWidth }) => ($fullWidth ? '100%' : 'auto')};
`
export default function Button({
children,
disabled = false,
fullWidth = false, // 👈 prop은 그대로 받지만
onClick,
...props
}) {
return (
<S.Button
$fullWidth={fullWidth} // 👈 styled-component에 전달할 때 $ 추가
disabled={disabled} // 👈 HTML 기본 속성은 $ 불필요
onClick={onClick} // 👈 HTML 기본 속성은 $ 불필요
{...props}
>
{children}
</S.Button>
)
}