Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/rules/jsx-key.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ Array.from([1, 2, 3], (x) => <Hello>{x}</Hello>);
<Hello {...{ key: id, id, caption }} />
```

```jsx
arr = [];
arr.push(<Hello />);
```

In the last example the key is being spread, which is currently possible, but discouraged in favor of the statically provided key.

Examples of **correct** code for this rule:
Expand All @@ -47,6 +52,11 @@ Array.from([1, 2, 3], (x) => <Hello key={x}>{x}</Hello>);
<Hello key={id} {...{ id, caption }} />
```

```jsx
arr = [];
arr.push(<Hello key="hello" />);
```

## Rule Options

```js
Expand Down
16 changes: 16 additions & 0 deletions lib/rules/jsx-key.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,22 @@ module.exports = {
}
},

// eslint-disable-next-line no-multi-str
'CallExpression[callee.type="MemberExpression"][callee.property.name=/^push|unshift|splice|with|concat$/],\
CallExpression[callee.type="OptionalMemberExpression"][callee.property.name=/^push|unshift|splice|with|concat$/],\
OptionalCallExpression[callee.type="MemberExpression"][callee.property.name=/^push|unshift|splice|with|concat$/],\
OptionalCallExpression[callee.type="OptionalMemberExpression"][callee.property.name=/^push|unshift|splice|with|concat$/]'(node) {
node.arguments.forEach((arg) => {
if (arg.type === 'JSXElement' && !hasProp(arg.openingElement.attributes, 'key')) {
report(context, messages.missingIterKey, 'missingArrayKey', { node });
return;
}
if (arg.type === 'JSXFragment') {
report(context, messages.missingIterKey, 'missingArrayKeyUsePrag', { node });
}
});
},

// Array.prototype.map
// eslint-disable-next-line no-multi-str
'CallExpression[callee.type="MemberExpression"][callee.property.name="map"],\
Expand Down
14 changes: 14 additions & 0 deletions tests/lib/rules/jsx-key.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,12 @@ ruleTester.run('jsx-key', rule, {
`,
settings,
},
{
code: 'arr.push(<App key="key" />);',
},
{
code: 'arr.push(<React.Fragment key="key" />);',
},
]),
invalid: parsers.all([
{
Expand Down Expand Up @@ -424,5 +430,13 @@ ruleTester.run('jsx-key', rule, {
options: [{ checkKeyMustBeforeSpread: true }],
errors: [{ messageId: 'keyBeforeSpread' }],
},
{
code: 'arr.push(<App />);',
errors: [{ messageId: 'missingArrayKey' }],
},
{
code: 'arr.push(<></>);',
errors: [{ messageId: 'missingArrayKeyUsePrag' }],
},
]),
});
Loading