[Error] React does not recognize the ‘isYearEnd’ prop on a DOM element.

1

해결된 오류 모음

목록 보기
5/5
post-thumbnail

혹시나 잘못된 개념 전달이 있다면 댓글 부탁드립니다. 저의 성장의 도움이 됩니다.

DOM의 attribute 소문자 변경 오류

연말 이벤트 관련해서 특정 기간에만 이벤트 문구로 변경해달라는 요청이 들어왔다.

  • isYearEnd (boolean 값)

styled-components를 사용해서 스타일링을 했고,
연말임을 판별하는 props를 전달하여 css에 조건을 걸었다.

그랬더니

React does not recognize the ‘isYearEnd’ prop on a DOM element....

카멜케이스 대신 소문자로 변환하라는 콘솔 오류가 발생했다.
프로젝트를 진행하면서 해당 오류를 간혹 접했었다. 콘솔에 에러가 뜨면 수정하는 방식으로 작업하다가 정확히 어느 경우에 에러가 발생하는지 알아보고 싶었다.


해결 방법

  • Transient props : props 앞에 $ 추가
<h1>
  	<Highlight $isYearEnd={isYearEnd}>연말맞이</Highlight> 
	이벤트 진행 중
</h1>
const Highlight = styled.span`
	diplay: ${({$isYearEnd}) => $isYearEnd ? 'inline' : 'none' };
`;

설명

React에서 props를 작성할때 카멜케이스 사용한다.

커스텀 컴포넌트에 전달하는 props는 카멜케이스를 사용해도 오류가 발생하지 않지만, styled-components에 전달하는 props는 카멜케이스를 사용할 경우 위와 같은 오류가 발생했다.

  • 커스텀 컴포넌트의 props
  • html의 attribute

오류의 원인을 찾아보며 props가 데이터를 전달하는 용도 로 단순하게 생각했다는 것을 깨달았다.

이런 오류는 보통 styled-components에서 css 변경을 위한 데이터 전달로 props를 정의했을때 발생한다.

If you want to prevent props meant to be consumed by styled components from being passed to the underlying React node or rendered to the DOM element, you can prefix the prop name with a dollar sign ($), turning it into a transient prop.
— 출처: styled-components 공식문서

공식문서에 의하면 styled-components의 props는 React 노드나 DOM 요소에 전달이 되므로 html 태그에 정의되지 않는 값을 추가하여 오류가 발생한 것이다.

그래서 console 오류에 나온 방법으로 소문자로 변경하더라고 [styled-components] props error 해결에서 적힌 오류가 발생할 수도 있다.
(기존엔 간단하게 소문자로 변환했었는데 명확한 해결책이 아니었다.)

html 태그에 속성이라고 전달하지 않는 방법은 styled-components 공식문서에서 찾아볼 수 있었다. 더 간단하다!!
(아래 코드는 공식문서에서 따옴)

const Comp = styled.div`
  color: ${props =>
    props.$draggable || 'black'};
`;

render(
  <Comp $draggable="red" draggable="true">
    Drag me!
  </Comp>
);

draggable은 html 속성으로 이미 정의가 되어있다. mdn에 의하면 draggable은 boolean 값을 가지는데, 위의 예시에서는 스타일링을 위한 데이터 전달로 사용되었다. (이름만 같았을 뿐)
그래서 $을 붙여주므로써 임의로 데이터 전달을 위한 props라는 의미로 $draggable 를 사용할 수 있는 것이다.


참고

styled-components 공식문서 : using-custom-props
styled-components 공식문서 : transient-props
[React] props는 attribute의 개념과 같을까?
[styled-components] props error 해결

0개의 댓글