Skip to content

Commit 925450f

Browse files
🔧 Fix for usage of React.Children methods
Fixes the case where you are iterating over a children prop via the React.Children API.
1 parent 8ef86c5 commit 925450f

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

‎lib/rules/no-array-index-key.js

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,32 @@ module.exports = {
4747
&& indexParamNames.indexOf(node.name) !== -1;
4848
}
4949

50+
function isUsingReactChildren(node) {
51+
const callee = node.callee;
52+
if (
53+
!callee
54+
|| !callee.property
55+
|| !callee.object
56+
) {
57+
return null;
58+
}
59+
60+
const isReactChildMethod = ['map', 'forEach'].indexOf(callee.property.name) > -1;
61+
if (!isReactChildMethod) {
62+
return null;
63+
}
64+
65+
const obj = callee.object;
66+
if (obj && obj.name === 'Children') {
67+
return true;
68+
}
69+
if (obj && obj.object && obj.object.name === 'React') {
70+
return true;
71+
}
72+
73+
return false;
74+
}
75+
5076
function getMapIndexParamName(node) {
5177
const callee = node.callee;
5278
if (callee.type !== 'MemberExpression') {
@@ -59,16 +85,19 @@ module.exports = {
5985
return null;
6086
}
6187

62-
const firstArg = node.arguments[0];
63-
if (!firstArg) {
88+
const callbackArg = isUsingReactChildren(node)
89+
? node.arguments[1]
90+
: node.arguments[0];
91+
92+
if (!callbackArg) {
6493
return null;
6594
}
6695

67-
if (!astUtil.isFunctionLikeExpression(firstArg)) {
96+
if (!astUtil.isFunctionLikeExpression(callbackArg)) {
6897
return null;
6998
}
7099

71-
const params = firstArg.params;
100+
const params = callbackArg.params;
72101

73102
const indexParamPosition = iteratorFunctionsToIndexParamPosition[callee.property.name];
74103
if (params.length < indexParamPosition + 1) {
@@ -132,24 +161,20 @@ module.exports = {
132161
&& ['createElement', 'cloneElement'].indexOf(node.callee.property.name) !== -1
133162
&& node.arguments.length > 1
134163
) {
135-
// React.createElement
136164
if (!indexParamNames.length) {
137165
return;
138166
}
139-
140167
const props = node.arguments[1];
141168

142169
if (props.type !== 'ObjectExpression') {
143170
return;
144171
}
145-
146172
props.properties.forEach(prop => {
147173
if (!prop.key || prop.key.name !== 'key') {
148174
// { ...foo }
149175
// { foo: bar }
150176
return;
151177
}
152-
153178
checkPropValue(prop.value);
154179
});
155180

0 commit comments

Comments
 (0)