TIL

230904) Styled-component로 props 를 전달할 때 콘솔 에러 발생

유이 YUI 2023. 9. 4. 18:57

 

 <s.LikesBar likes={likesPercentage.toFixed(0)}>

1. jsx로 LikesBar를 지정하고 Style 컴포넌트를 분리하여 likes라는 Props를 스타일 컴포넌트로 넘겨주고 있는 상황.

width: ${(props) => props.likes}%;

2. Props 를 넘겨 받는 이유: width 를 Likes 비율만큼 늘려줘야 하는 상황이기 때문에!

 

요로케 말입니다... 또가요 / 안가요 비율에 따라 움직이게 만들어야 하는 상황!

하지만 이렇게 코드를 두면 아래와 같은 콘솔 워닝이 나타났습니다!

 


 

styled-components: it looks like an unknown prop "likes" is being sent through to the DOM, which will likely trigger a React console error. If you would like automatic filtering of unknown props, you can opt-into that behavior via `<StyleSheetManager shouldForwardProp={...}>` (connect an API like `@emotion/is-prop-valid`) or consider using transient props (`$` prefix for automatic filtering.)

 


 

결론적으로 해결 방법은 GPT 를 적극 활용하여 해결하였습니다. props를 넘겨 받는 부분에서 $를 사용하라는 말이 있어서 해 봤지만 잘 안 됐고, 아래 방법을 통하여 해결해 낼 수 있었습니다!

 

1. jsx 부분 컴포넌트에 해당 내용을 추가해줍니다. 컴포넌트 내용 부분에 기존 return 이후의 모든 jsx 부분을 넣어 주시면 됩니다!

<StyleSheetManager shouldForwardProp={prop => isPropValid(prop)}>
    {/* 컴포넌트 내용 */}
  </StyleSheetManager>

 

2. 이후에 @emotion/is-prop-valid 라이브러리를 설치해 줍니다. 저는 yarn을 이용하고 있기 때문에 yarn add @emotion/is-prop-valid를 해 주었습니다!

 

3. StyleSheetManager과 isPropValid 를 각각 import 해 줍니다.

import { StyleSheetManager } from "styled-components";
import isPropValid from "@emotion/is-prop-valid";

 

이제 더 이상 Warning 없이 깨끗해진 콘솔을 확인할 수 있습니다 ^.^

 


 

 

브이하는 사진

오늘도 잘 해냈다!