[React, Styled-component] If you want to write it to the DOM, pass a string instead 해결하기 -> prefix $ 붙여주기

thousand_yj·2023년 8월 11일
0

Willing 프로젝트

목록 보기
17/18

문제상황

If you want to write it to the DOM, pass a string instead.

위와 같은 에러가 발생하길래 코드를 살펴봤더니 태그로 boolean 요소를 넘겨줬을 때 발생했다. 구글링을 해보니 styled-components를 쓸 때 발생하는 상황이라고 한다.

가령 보여지는 여부를 결정하는 visible 상태를 다음과 같이 전달하려고 하면 콘솔창에서 에러가 발생한다.

<Ul visible={props.isUlVisible}>
  
// ...
const Ul = styled.ul<{ visible: boolean }>`
  display: ${(props) => (props.visible ? "block" : "none")};
  // ...
`

코드 상으로는 에러가 없어보이는데 계속 콘솔창에서는 boolean 값이 아니라고 하니... 다음과 같이 코드를 변경했다.

<Ul visible={props.isUlVisible ? 1 : 0}>
  
// ...
const Ul = styled.ul<{ visible: number }>`
  display: ${(props) => (props.visible ? "block" : "none")};
  // ...
`

js의 truthy, falsy 로직으로 최대한 코드의 수정이 적게 수정했다.

다른 방법 (prefix $ 사용)

아니면 새롭게 v5.1부터 추가된 기능을 사용해도 된다.
prefix 로 $를 사용하게 되면, props가 실제 DOM 요소에 전달되는 것을 막는다. 공식문서는 여기를 참고하자.

<Ul $visible={props.isUlVisible}>
  
// ...
const Ul = styled.ul<{ $visible: boolean }>`
  display: ${(props) => (props.$visible ? "block" : "none")};
  // ...
`

두번째 방식이 더 직관적이라고 생각하여 전부 2번째 방법으로 바꿨다.

unknown prop is being sent through to the DOM, ... 경고

styled-components: it looks like an unknown prop "colorstring" 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.)

이 경로도 동일하게 앞에 $ 붙여줘서 해결했다

profile
함께 일하고 싶은 개발자가 되기 위해 노력합니다. 코딩테스트 관련 공부 및 이야기는 티스토리에도 업로드되어 있습니다.

0개의 댓글