Skip to content

Commit

Permalink
Ignore jsx-key if inside React.Children.toArray()
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
silvenon committed Dec 10, 2017
1 parent f6e4c89 commit 82d0258
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
27 changes: 27 additions & 0 deletions lib/rules/jsx-key.js
Expand Up @@ -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;
}
Expand All @@ -52,6 +75,10 @@ module.exports = {

// Array.prototype.map
CallExpression: function (node) {
if (isWithinChildrenToArray) {
return;
}

if (node.callee && node.callee.type !== 'MemberExpression') {
return;
}
Expand Down
10 changes: 9 additions & 1 deletion tests/lib/rules/jsx-key.js
Expand Up @@ -37,7 +37,15 @@ ruleTester.run('jsx-key', rule, {
{code: '[1, 2, 3].foo(x => <App />);'},
{code: 'var App = () => <div />;'},
{code: '[1, 2, 3].map(function(x) { return; });'},
{code: 'foo(() => <div />);'}
{code: 'foo(() => <div />);'},
// #1574
{code: 'React.Children.toArray([1, 2 ,3].map(x => <App />));'},
{
code: `
import { Children } from "react";
Children.toArray([1, 2 ,3].map(x => <App />));
`
}
],
invalid: [{
code: '[<App />];',
Expand Down

0 comments on commit 82d0258

Please sign in to comment.