Skip to content

Commit

Permalink
🔧 Fix for usage of React.Children methods
Browse files Browse the repository at this point in the history
Fixes the case where you are iterating over a children prop via the
React.Children API.
  • Loading branch information
himynameisdave committed Dec 13, 2018
1 parent 8ef86c5 commit 925450f
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions lib/rules/no-array-index-key.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,32 @@ module.exports = {
&& indexParamNames.indexOf(node.name) !== -1;
}

function isUsingReactChildren(node) {
const callee = node.callee;
if (
!callee
|| !callee.property
|| !callee.object
) {
return null;
}

const isReactChildMethod = ['map', 'forEach'].indexOf(callee.property.name) > -1;
if (!isReactChildMethod) {
return null;
}

const obj = callee.object;
if (obj && obj.name === 'Children') {
return true;
}
if (obj && obj.object && obj.object.name === 'React') {
return true;
}

return false;
}

function getMapIndexParamName(node) {
const callee = node.callee;
if (callee.type !== 'MemberExpression') {
Expand All @@ -59,16 +85,19 @@ module.exports = {
return null;
}

const firstArg = node.arguments[0];
if (!firstArg) {
const callbackArg = isUsingReactChildren(node)
? node.arguments[1]
: node.arguments[0];

if (!callbackArg) {
return null;
}

if (!astUtil.isFunctionLikeExpression(firstArg)) {
if (!astUtil.isFunctionLikeExpression(callbackArg)) {
return null;
}

const params = firstArg.params;
const params = callbackArg.params;

const indexParamPosition = iteratorFunctionsToIndexParamPosition[callee.property.name];
if (params.length < indexParamPosition + 1) {
Expand Down Expand Up @@ -132,24 +161,20 @@ module.exports = {
&& ['createElement', 'cloneElement'].indexOf(node.callee.property.name) !== -1
&& node.arguments.length > 1
) {
// React.createElement
if (!indexParamNames.length) {
return;
}

const props = node.arguments[1];

if (props.type !== 'ObjectExpression') {
return;
}

props.properties.forEach(prop => {
if (!prop.key || prop.key.name !== 'key') {
// { ...foo }
// { foo: bar }
return;
}

checkPropValue(prop.value);
});

Expand Down

0 comments on commit 925450f

Please sign in to comment.