Skip to content

Commit e23c200

Browse files
committed
fix: fix scope check in no-unnecessary-key rule
1 parent 7811324 commit e23c200

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

packages/plugins/eslint-plugin-react-x/src/rules/no-unnecessary-key.spec.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,5 +79,13 @@ ruleTester.run(RULE_NAME, rule, {
7979
tsx`
8080
<div><p key='static-child-key' /></div>
8181
`,
82+
// Valid: not a list rendering context
83+
tsx`
84+
things.map(thing => {
85+
function NestedComponent() {
86+
return <span key='foo'><span key='bar' /></span>;
87+
}
88+
})
89+
`,
8290
],
8391
});

packages/plugins/eslint-plugin-react-x/src/rules/no-unnecessary-key.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,14 @@ export default createRule<[], MessageID>({
3535
});
3636

3737
export function create(context: RuleContext<MessageID, []>): RuleListener {
38-
if (!context.sourceCode.getText().includes("key=")) {
39-
return {};
40-
}
41-
38+
if (!context.sourceCode.text.includes("key=")) return {};
4239
return {
4340
JSXAttribute(node: TSESTree.JSXAttribute) {
4441
if (node.name.name !== "key") return;
4542
const jsxElement = node.parent.parent;
43+
const initialScope = context.sourceCode.getScope(jsxElement);
4644
const pMapCallback = AST.findParentNode(jsxElement, isMapCallback);
47-
if (pMapCallback == null) return;
45+
if (pMapCallback == null || context.sourceCode.getScope(pMapCallback) !== initialScope) return;
4846
const pKeyedElementOrElse = AST.findParentNode(
4947
jsxElement,
5048
(n) => {

0 commit comments

Comments
 (0)