styled-components DOM issue

young_pallete·2021년 6월 11일
11

Issues

목록 보기
1/6

React does not recognize the keywordType prop on a DOM element.
If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase keywordtype instead.
If you accidentally passed it from a parent component, remove it from the DOM element.


때때로 styled-components로 작업을 하다 보면 다음과 같은 문구를 보게 된다.
아무래도, react-router-dom에서 prop을 저렇게 대문자로 기입할 때 나오는 에러인 듯 싶다.

커스텀 속성 으로써 DOM에 나타내고 싶다면 lower case로 attributes name을 바꿔 사용하거나, 의도치 않게 위에서 내려온 prop이면 제거하라

는 말이었는데, 나는 전자였다.

그래서 소문자로 바꾸면 에러는 사라지지만, 나는 고집쟁이라. 대문자로 표기해도 되는 방법을 찾고 싶었다. 결국 엄청난 삽질 끝에, 결국 공식문서에 답이 있었다는 것을 찾아냈다.

const SearchDataItem = styled(Link)`
	${props =>
    		props.keywordType === 'user' && css`
            	...(생략)
            `
     }
`

<SearchDataItem keywordType={keywordType} to={`/@${data.userId}`}>
	<UserImage userImage={data.userImage}/>
	<Nickname>{data.nickname}</Nickname>
	<Username>{`(${data.userId})`}</Username>
</SearchDataItem>
                               

이런 내용이었는데, 이를 에러가 안 나오게 하려면 간단하다. 앞에 $을 써주면 된다고 한다.
해당 기능은 5.1버전부터 가능하다고 한다.

// after
const SearchDataItem = styled(Link)`
	${props =>
    		props.$keywordType === 'user' && css`
            	...(생략)
            `
     }
`

<SearchDataItem $keywordType={keywordType} to={`/@${data.userId}`}>
	<UserImage userImage={data.userImage}/>
	<Nickname>{data.nickname}</Nickname>
	<Username>{`(${data.userId})`}</Username>
</SearchDataItem>

$사인으로 표기한 props는 styled-components에서 transient props라고 명명되어 있는데, 이는 단순히 스타일만을 위한 변수가 기본 React 노드로 전달되거나 DOM 요소로 렌더링되는 것을 방지할 때 사용 가능한 prop이다!

출처: styled component document

profile
People are scared of falling to the bottom but born from there. What they've lost is nth. 😉

0개의 댓글