Skip to content

Commit 27cb8bf

Browse files
committed
Added support (without options ... which are still to come) for spread (ie. ...) arguments with keys to be considered as valid as explicit key attributes
Part of jsx-eslint#1753
1 parent 03df672 commit 27cb8bf

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/rules/jsx-key.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,25 @@ module.exports = {
4545
const fragmentPragma = pragmaUtil.getFragmentFromContext(context);
4646

4747
function checkIteratorElement(node) {
48-
if (node.type === 'JSXElement' && !hasProp(node.openingElement.attributes, 'key')) {
48+
if (node.type === 'JSXElement') {
49+
const hasAKeyAttribute = hasProp(node.openingElement.attributes, 'key');
50+
51+
const hasASpreadArgumentWithAKeyProperty = node.openingElement
52+
&& node.openingElement.attributes
53+
&& node.openingElement.attributes.some(
54+
({argument}) => argument && argument.properties && argument.properties.some(
55+
(property) => property.key.name === 'key'));
56+
57+
const hasAnObjectSpreadArgument = node.openingElement
58+
&& node.openingElement.attributes
59+
&& node.openingElement.attributes.some(
60+
({argument}) => argument && argument.type === 'Identifier');
61+
62+
const isValidElement = hasAKeyAttribute
63+
|| hasASpreadArgumentWithAKeyProperty
64+
|| hasAnObjectSpreadArgument;
65+
if (isValidElement) return;
66+
4967
context.report({
5068
node,
5169
message: 'Missing "key" prop for element in iterator'

tests/lib/rules/jsx-key.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ ruleTester.run('jsx-key', rule, {
3939
{code: 'fn()'},
4040
{code: '[1, 2, 3].map(function () {})'},
4141
{code: '<App />;'},
42+
{code: '[1, 2, 3].map(x => <App {...{ key }} />);'},
43+
{code: '[1, 2, 3].map(x => <App {...objectWithKey} />);'},
4244
{code: '[<App key={0} />, <App key={1} />];'},
4345
{code: '[1, 2, 3].map(function(x) { return <App key={x} /> });'},
4446
{code: '[1, 2, 3].map(x => <App key={x} />);'},

0 commit comments

Comments
 (0)