Skip to content

Commit 82d0258

Browse files
committed
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 jsx-eslint#1574.
1 parent f6e4c89 commit 82d0258

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

lib/rules/jsx-key.js

+27
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,31 @@ module.exports = {
3636
return body.filter(item => item.type === 'ReturnStatement')[0];
3737
}
3838

39+
const childrenToArraySelector = `:matches(
40+
CallExpression
41+
[callee.object.object.name=React]
42+
[callee.object.property.name=Children]
43+
[callee.property.name=toArray],
44+
CallExpression
45+
[callee.object.name=Children]
46+
[callee.property.name=toArray]
47+
)`.replace(/\s/g, '');
48+
let isWithinChildrenToArray = false;
49+
3950
return {
51+
[childrenToArraySelector]: function() {
52+
isWithinChildrenToArray = true;
53+
},
54+
55+
[`${childrenToArraySelector}:exit`]: function() {
56+
isWithinChildrenToArray = false;
57+
},
58+
4059
JSXElement: function(node) {
60+
if (isWithinChildrenToArray) {
61+
return;
62+
}
63+
4164
if (hasProp(node.openingElement.attributes, 'key')) {
4265
return;
4366
}
@@ -52,6 +75,10 @@ module.exports = {
5275

5376
// Array.prototype.map
5477
CallExpression: function (node) {
78+
if (isWithinChildrenToArray) {
79+
return;
80+
}
81+
5582
if (node.callee && node.callee.type !== 'MemberExpression') {
5683
return;
5784
}

tests/lib/rules/jsx-key.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,15 @@ ruleTester.run('jsx-key', rule, {
3737
{code: '[1, 2, 3].foo(x => <App />);'},
3838
{code: 'var App = () => <div />;'},
3939
{code: '[1, 2, 3].map(function(x) { return; });'},
40-
{code: 'foo(() => <div />);'}
40+
{code: 'foo(() => <div />);'},
41+
// #1574
42+
{code: 'React.Children.toArray([1, 2 ,3].map(x => <App />));'},
43+
{
44+
code: `
45+
import { Children } from "react";
46+
Children.toArray([1, 2 ,3].map(x => <App />));
47+
`
48+
}
4149
],
4250
invalid: [{
4351
code: '[<App />];',

0 commit comments

Comments
 (0)