From 82d02582e4ff88581a0a7b99bd69d4f39f36dd24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matija=20Marohni=C4=87?= Date: Sun, 10 Dec 2017 15:52:25 +0100 Subject: [PATCH] Ignore jsx-key if inside React.Children.toArray() jsx-key rule should always succeed if we're inside React.Children.toArray() because omitting the key there doesn't cause a React warning. Fixes #1574. --- lib/rules/jsx-key.js | 27 +++++++++++++++++++++++++++ tests/lib/rules/jsx-key.js | 10 +++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/rules/jsx-key.js b/lib/rules/jsx-key.js index ccc91a470e..e4e9adf5fc 100644 --- a/lib/rules/jsx-key.js +++ b/lib/rules/jsx-key.js @@ -36,8 +36,31 @@ module.exports = { return body.filter(item => item.type === 'ReturnStatement')[0]; } + const childrenToArraySelector = `:matches( + CallExpression + [callee.object.object.name=React] + [callee.object.property.name=Children] + [callee.property.name=toArray], + CallExpression + [callee.object.name=Children] + [callee.property.name=toArray] + )`.replace(/\s/g, ''); + let isWithinChildrenToArray = false; + return { + [childrenToArraySelector]: function() { + isWithinChildrenToArray = true; + }, + + [`${childrenToArraySelector}:exit`]: function() { + isWithinChildrenToArray = false; + }, + JSXElement: function(node) { + if (isWithinChildrenToArray) { + return; + } + if (hasProp(node.openingElement.attributes, 'key')) { return; } @@ -52,6 +75,10 @@ module.exports = { // Array.prototype.map CallExpression: function (node) { + if (isWithinChildrenToArray) { + return; + } + if (node.callee && node.callee.type !== 'MemberExpression') { return; } diff --git a/tests/lib/rules/jsx-key.js b/tests/lib/rules/jsx-key.js index 4bea4bd5ee..dc9626667b 100644 --- a/tests/lib/rules/jsx-key.js +++ b/tests/lib/rules/jsx-key.js @@ -37,7 +37,15 @@ ruleTester.run('jsx-key', rule, { {code: '[1, 2, 3].foo(x => );'}, {code: 'var App = () =>
;'}, {code: '[1, 2, 3].map(function(x) { return; });'}, - {code: 'foo(() =>
);'} + {code: 'foo(() =>
);'}, + // #1574 + {code: 'React.Children.toArray([1, 2 ,3].map(x => ));'}, + { + code: ` + import { Children } from "react"; + Children.toArray([1, 2 ,3].map(x => )); + ` + } ], invalid: [{ code: '[];',