Skip to content

Commit

Permalink
Added support (without options ... which are still to come) for sprea…
Browse files Browse the repository at this point in the history
…d (ie. ...) arguments with keys to be considered as valid as explicit key attributes

Part of jsx-eslint#1753
  • Loading branch information
machineghost committed Jun 8, 2020
1 parent 03df672 commit 27cb8bf
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
20 changes: 19 additions & 1 deletion lib/rules/jsx-key.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,25 @@ module.exports = {
const fragmentPragma = pragmaUtil.getFragmentFromContext(context);

function checkIteratorElement(node) {
if (node.type === 'JSXElement' && !hasProp(node.openingElement.attributes, 'key')) {
if (node.type === 'JSXElement') {
const hasAKeyAttribute = hasProp(node.openingElement.attributes, 'key');

const hasASpreadArgumentWithAKeyProperty = node.openingElement
&& node.openingElement.attributes
&& node.openingElement.attributes.some(
({argument}) => argument && argument.properties && argument.properties.some(
(property) => property.key.name === 'key'));

const hasAnObjectSpreadArgument = node.openingElement
&& node.openingElement.attributes
&& node.openingElement.attributes.some(
({argument}) => argument && argument.type === 'Identifier');

const isValidElement = hasAKeyAttribute
|| hasASpreadArgumentWithAKeyProperty
|| hasAnObjectSpreadArgument;
if (isValidElement) return;

context.report({
node,
message: 'Missing "key" prop for element in iterator'
Expand Down
2 changes: 2 additions & 0 deletions tests/lib/rules/jsx-key.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ ruleTester.run('jsx-key', rule, {
{code: 'fn()'},
{code: '[1, 2, 3].map(function () {})'},
{code: '<App />;'},
{code: '[1, 2, 3].map(x => <App {...{ key }} />);'},
{code: '[1, 2, 3].map(x => <App {...objectWithKey} />);'},
{code: '[<App key={0} />, <App key={1} />];'},
{code: '[1, 2, 3].map(function(x) { return <App key={x} /> });'},
{code: '[1, 2, 3].map(x => <App key={x} />);'},
Expand Down

0 comments on commit 27cb8bf

Please sign in to comment.