Skip to content

Commit

Permalink
Check key in JSX spread attribute (jsx-key) (#129)
Browse files Browse the repository at this point in the history
This looks for `key` in an object literal being spread into the component.
  • Loading branch information
jomasti authored and adidahiya committed Dec 14, 2017
1 parent 31d2987 commit a4a5906
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/rules/jsxKeyRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ import {
isBlock,
isCallExpression,
isFunctionExpression,
isIdentifier,
isJsxAttribute,
isJsxElement,
isJsxSelfClosingElement,
isJsxSpreadAttribute,
isObjectLiteralExpression,
isParenthesizedExpression,
isPropertyAccessExpression,
isReturnStatement,
Expand Down Expand Up @@ -88,11 +91,12 @@ function walk(ctx: Lint.WalkContext<void>): void {
}

function checkIteratorElement(node: ts.Node, ctx: Lint.WalkContext<void>) {
if (isJsxElement(node) && !hasKeyProp(node.openingElement.attributes)) {
if (isJsxElement(node) && !hasKeyProp(node.openingElement.attributes) &&
!hasKeyPropSpread(node.openingElement.attributes)) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
}

if (isJsxSelfClosingElement(node) && !hasKeyProp(node.attributes)) {
if (isJsxSelfClosingElement(node) && !hasKeyProp(node.attributes) && !hasKeyPropSpread(node.attributes)) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
}
}
Expand All @@ -103,6 +107,16 @@ function hasKeyProp(attributes: ts.JsxAttributes) {
.indexOf(true) !== -1;
}

function hasKeyPropSpread(attributes: ts.JsxAttributes) {
return attributes.properties.some((prop) => (
isJsxSpreadAttribute(prop) &&
isObjectLiteralExpression(prop.expression) &&
prop.expression.properties.some((expProp) => (
expProp.name !== undefined && isIdentifier(expProp.name) && expProp.name.text === "key"
))
));
}

function getReturnStatement(body: ts.NodeArray<ts.Statement>) {
return body.filter((item) => isReturnStatement(item))[0] as ts.ReturnStatement | undefined;
}
2 changes: 2 additions & 0 deletions test/rules/jsx-key/test.tsx.lint
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ var App = () => <div />;
[1, 2, 3].map(function(x) { return; });
foo(() => <div />)
[<App />];
[1, 2, 3].map((x, idx) => <App {...{x: x, key: idx}} />);
[1, 2, 3].map((x, key) => <App {...{x, key}} />);

[<App {...key} />];
~~~~~~~~~~~~~~~~ [0]
Expand Down

0 comments on commit a4a5906

Please sign in to comment.