styled-componentsに独自のpropsを生やして値を渡したら怒られたときのメモ

2行

  • 独自に生やしたpropsをまるごと渡してはいけない
  • 分割代入でdomのattributesに定義がないpropsを間引く

エラーメッセージ

なんかこういう2種類のやつを言われる

React does not recognize the `isAvailable` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `isAvailable` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
Received `false` for a non-boolean attribute `isAvailable`.

If you want to write it to the DOM, pass a string instead: isAvailable="false" or isAvailable={value.toString()}.

If you used to conditionally omit it with isAvailable={condition && value}, pass isAvailable={condition ? value : undefined} instead.

結論としては、どっちのエラーメッセージも本来のDOMのAttributeにないプロパティを生やそうとしているから怒られている。

コード

const StyledIcon = styled(
  (props: { isAvailable: boolean }) => (
    <Icon {...props} />
  ),
)`
  width: 10px;
  opacity: ${({ isAvailable }) => (isAvailable ? '1' : '.8')};
`

// こんな感じに普通にbooleanを渡していた
<StyledIcon isAvailable={myAvailableCondition} />

trueならopacityが1そうでないなら0.8にするようにしているコンポーネント

解決

そもそも本件、公式FAQに書かれていた。

www.styled-components.com

const StyledArrowStepIcon = styled(
  ({ isAvailable, ...props }: { isAvailable: boolean }) => (
    <ArrowStepIcon {...props} />
  ),
)`
  width: 10px;
  opacity: ${({ isAvailable }) => (isAvailable ? '1' : '.8')};
`

こうすればOK。 分割代入で独自に生やしているprops(isAvailable)を取り出して、残りをスプレッドオペレータで...propsにまとめる。こうすると独自のPropsを間引いたpropsができる。 あとは間引いたpropsをそのままコンポーネントに渡せばOK。


解決してから普通にわかるシリーズ。

無駄にハマってしまったので書いた。