Skip to content

Commit

Permalink
Add checkFragmentShorthand option
Browse files Browse the repository at this point in the history
  • Loading branch information
kaykayehnn committed Jun 22, 2019
1 parent ed04c2f commit 7c1abed
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
24 changes: 22 additions & 2 deletions lib/rules/jsx-key.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ const docsUrl = require('../util/docsUrl');
// Rule Definition
// ------------------------------------------------------------------------------

const defaultOptions = {
checkFragmentShorthand: false
}

module.exports = {
meta: {
docs: {
Expand All @@ -21,17 +25,29 @@ module.exports = {
recommended: true,
url: docsUrl('jsx-key')
},
schema: []
schema: [{
type: 'object',
properties: {
checkFragmentShorthand: {
type: 'boolean',
default: defaultOptions.checkFragmentShorthand
}
},
additionalProperties: false
}]
},

create(context) {
const options = Object.assign({}, defaultOptions, context.options[0])
const checkFragmentShorthand = options.checkFragmentShorthand

function checkIteratorElement(node) {
if (node.type === 'JSXElement' && !hasProp(node.openingElement.attributes, 'key')) {
context.report({
node,
message: 'Missing "key" prop for element in iterator'
});
} else if (node.type === 'JSXFragment') {
} else if (checkFragmentShorthand && node.type === 'JSXFragment') {
context.report({
node,
message: 'Missing "key" prop for element in iterator. Shorthand fragment syntax does support providing keys'
Expand All @@ -58,6 +74,10 @@ module.exports = {
},

JSXFragment(node) {
if (!checkFragmentShorthand) {
return;
}

if (node.parent.type === 'ArrayExpression') {
context.report({
node,
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 @@ -64,10 +64,12 @@ ruleTester.run('jsx-key', rule, {
}, {
code: '[1, 2, 3].map(x => <>{x}</>);',
parser: parsers.BABEL_ESLINT,
options: [{checkFragmentShorthand: true}],
errors: [{message: 'Missing "key" prop for element in iterator. Shorthand fragment syntax does support providing keys'}]
}, {
code: '[<></>];',
parser: parsers.BABEL_ESLINT,
options: [{checkFragmentShorthand: true}],
errors: [{message: 'Missing "key" prop for element in array. Shorthand fragment syntax does support providing keys'}]
}]
});

0 comments on commit 7c1abed

Please sign in to comment.