Skip to content

Commit

Permalink
[Fix] jsx-key: include duplicate-keyed jsx children in `warnDuplica…
Browse files Browse the repository at this point in the history
…tes` option

See #2614 (comment); fixes #2614.
  • Loading branch information
ljharb committed Feb 23, 2022
1 parent 6d6f5bd commit f51ec45
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/rules/jsx-key.js
Expand Up @@ -104,9 +104,11 @@ module.exports = {
});
}

const seen = new WeakSet();

return {
ArrayExpression(node) {
const jsx = node.elements.filter((x) => x.type === 'JSXElement');
'ArrayExpression, JSXElement > JSXElement'(node) {
const jsx = (node.type === 'ArrayExpression' ? node.elements : node.parent.children).filter((x) => x.type === 'JSXElement');
if (jsx.length === 0) {
return;
}
Expand All @@ -128,7 +130,7 @@ module.exports = {

if (checkKeyMustBeforeSpread && isKeyAfterSpread(attrs)) {
report(context, messages.keyBeforeSpread, 'keyBeforeSpread', {
node,
node: node.type === 'ArrayExpression' ? node : node.parent,
});
}
});
Expand All @@ -138,9 +140,12 @@ module.exports = {
if (warnOnDuplicates) {
values(map).filter((v) => v.length > 1).forEach((v) => {
v.forEach((n) => {
report(context, messages.nonUniqueKeys, 'nonUniqueKeys', {
node: n,
});
if (!seen.has(n)) {
seen.add(n);
report(context, messages.nonUniqueKeys, 'nonUniqueKeys', {
node: n,
});
}
});
});
}
Expand Down
15 changes: 15 additions & 0 deletions tests/lib/rules/jsx-key.js
Expand Up @@ -165,5 +165,20 @@ ruleTester.run('jsx-key', rule, {
{ messageId: 'nonUniqueKeys', line: 4 },
],
},
{
code: `
const div = (
<div>
<span key="notunique"/>
<span key="notunique"/>
</div>
);
`,
options: [{ warnOnDuplicates: true }],
errors: [
{ messageId: 'nonUniqueKeys', line: 4 },
{ messageId: 'nonUniqueKeys', line: 5 },
],
},
]),
});

0 comments on commit f51ec45

Please sign in to comment.