styled-components - Received `false` for a non-boolean attribute 에러 해결하기
포스트
취소

styled-components - Received `false` for a non-boolean attribute 에러 해결하기

styled-components를 사용하는데 콘솔에 경고가 떴다. image

내 코드는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const FormControl = styled.div`
  margin: 0.5rem 0;

  & label {
    font-weight: bold;
    display: block;
    margin-bottom: 0.5rem;
    color: ${(props) => (props.checkvalid ? 'red' : 'black')};
  }
`

//JSX
<FormControl checkvalid={!isValid}>
    <label>Label</label>
    <input type="text" />
</FormControl>

경고 내용을 보면 내가 보낸 props가 DOM으로 보내지는 것 처럼 보이고, 이는 React 콘솔 오류를 발생시킬 수 있다고 한다.
마지막 부분에 보면 다음과 같은 내용이 있다. consider using transient props ($ prefix for automatic filtering.)
여기서 말하는 transient props는 스타일이 지정되어있는 컴포넌트에서 사용해야 할 props가 DOM 요소로 렌더링되는 걸 방지할 수 있다고 한다.

  • transient props로 해결한 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const FormControl = styled.div`
  margin: 0.5rem 0;

  & label {
    font-weight: bold;
    display: block;
    margin-bottom: 0.5rem;
    color: ${(props) => (props.$checkvalid ? 'red' : 'black')};
  }
`

//JSX
<FormControl $checkvalid={!isValid}>
    <label>Label</label>
    <input type="text" />
</FormControl>

사용방법 : prop 이름 앞에 $를 붙인다. 이때 JSX코드에 있는 컴포넌트의 prop앞에도 붙여야 한다.


이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.