react type_error ai_generated true

TypeError: X is not a function. (In 'X()', 'X' is undefined) when using .map on children

ID: react/invalid-array-children-map

Also available as: JSON · Markdown · 中文
93%Fix Rate
88%Confidence
1Evidence
2023-06-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
React 18.2.0 active
React 17.0.2 active

Root Cause

The 'children' prop is not an array but a single React element, string, or undefined, so calling .map() on it fails.

generic

中文

children 属性不是一个数组,而是一个单独的 React 元素、字符串或 undefined,因此对其调用 .map() 会失败。

Official Documentation

https://react.dev/reference/react/Children#children-map

Workarounds

  1. 95% success Use React.Children.toArray(children) before calling .map() to safely convert children to an array, regardless of type.
    Use React.Children.toArray(children) before calling .map() to safely convert children to an array, regardless of type.
  2. 90% success Add a guard to check if children is an array before mapping. If not, wrap it in an array or handle single child separately.
    Add a guard to check if children is an array before mapping. If not, wrap it in an array or handle single child separately.

中文步骤

  1. Use React.Children.toArray(children) before calling .map() to safely convert children to an array, regardless of type.
  2. Add a guard to check if children is an array before mapping. If not, wrap it in an array or handle single child separately.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    If children is already an array (multiple children), this creates a nested array; .map won't iterate over individual children correctly.

  2. 60% fail

    React.Children.toArray returns an empty array for null/undefined, so .map works, but the real issue is that children might be a single element not in an array, which toArray handles but the user may not realize why.