CSS

[CSS] non-boolean attribute warning

hid1 2022. 9. 4. 16:52

 

Warning: Received `true` for a non-boolean attribute `속성`.
If you want to write it to the DOM, pass a string instead: 속성="true" or 속성={value.toString()}.

 

styled-components 사용 시 마주친 오류이다.

이 경고 메시지는 비표준 속성이  HTML DOM 요소에 첨부되고 있음을 나타낸다.

 

const Link = props => (
  <a {...props} className={props.className}>
    {props.text}
  </a>
)

const StyledComp = styled(Link)`
  color: ${props => (props.red ? 'red' : 'blue')};
`

<StyledComp text="Click" href="https://www.styled-components.com/" red />

위의 코드는 아래처럼 렌더링된다.

<a text="Click" href="https://www.styled-components.com/" red="true" class="[generated class]">Click</a>

React는 <a> 요소에 대해 유효한 HTML 속성이 아닌 "red"와 같은 비표준 속성이 첨부되는 경우에 위와 같은 경고를 준다.

 

원래 styled-components는 비표준 속성을 자동으로 필터링하여 DOM에 전달하지 않도록 되어있지만

DOM에 전달될 수 있는 속성으로 판단되는 경우가 있어 경고가 뜨는 것 같아 보였다.

 

해결 방법 styled-componets

1. transient props

(styled-componets 5.1 버전)

styled-componets가 사용하는 속성이 기본 React 노드로 전달되거나 DOM 요소로 렌더링되는 것을 방지하려면
속성 이름 앞에 달러 기호($)를 붙여 임시 속성으로 바꿀 수 있다.

 

<StyledComp text="Click" href="https://www.styled-components.com/" $red />

 

2. destructure props

5.1 이전 버전이나  transient props을 사용하지 못할 경우 destructure props을 사용할 수 있다.

const Link = ({ className, red, text, ...props }) => (
  <a {...props} className={className}>
    {text}
  </a>
)

const StyledComp = styled(Link)`
  color: ${props => (props.red ? 'red' : 'blue')};
`

<StyledComp text="Click" href="https://www.styled-components.com/" red />

이후 렌더링

<a href="https://www.styled-components.com/" class="[generated class]">Click</a>

 

위의 코드처럼  red와 text를 destructure하여 사용할 때 DOM에 전달되지 않게 된다.

 

 

 

 

 

emotion 사용 시에도 이 오류가 뜨는데 $기능을 제공하지 않는 것 같다. (명확한 해결방법을 아직 찾지 못했다..)

 


 

 

 

styled-components: FAQs

Commonly asked questions about styled-components

styled-components.com

 

반응형