Skip to content

Commit

Permalink
Use pragma settings to recognize fragment
Browse files Browse the repository at this point in the history
  • Loading branch information
golopot committed May 6, 2019
1 parent 45c895b commit da38763
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
16 changes: 11 additions & 5 deletions lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -3,29 +3,35 @@
*/

'use strict';
const pragmaUtil = require('../util/pragma');
const docsUrl = require('../util/docsUrl');

/**
* Test whether a JSXElement is a fragment
* @param {JSXElement} node
* @param {object} context
* @returns {boolean}
*/
function isFragment(node) {
function isFragment(node, context) {
const name = node.openingElement.name;
const reactPragma = pragmaUtil.getFromContext(context);
const fragmentPragma = pragmaUtil.getFragmentFromContext(context);

// <Fragment>
if (
name.type === 'JSXIdentifier'
&& name.name === 'Fragment'
&& name.name === fragmentPragma
) {
return true;
}

// <*.Fragment>
// <React.Fragment>
if (
name.type === 'JSXMemberExpression'
&& name.object.type === 'JSXIdentifier'
&& name.object.name === reactPragma
&& name.property.type === 'JSXIdentifier'
&& name.property.name === 'Fragment'
&& name.property.name === fragmentPragma
) {
return true;
}
Expand Down Expand Up @@ -84,7 +90,7 @@ module.exports = {

return {
JSXElement(node) {
if (isFragment(node)) {
if (isFragment(node, context)) {
checkChildrenLength(node);
}
},
Expand Down
13 changes: 10 additions & 3 deletions tests/lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -46,7 +46,8 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
parser: parsers.BABEL_ESLINT
},
'<NotFragment />',
'<React.NotFragment />'
'<React.NotFragment />',
'<NotReact.Fragment />'
],
invalid: [
{
Expand Down Expand Up @@ -78,10 +79,16 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
},
{
code: `
<Any.Fragment>
<SomeReact.SomeFragment>
{foo}
</Any.Fragment>
</SomeReact.SomeFragment>
`,
settings: {
react: {
pragma: 'SomeReact',
fragment: 'SomeFragment'
}
},
errors: [{messageId: 'NeedsMoreChidren'}]
},
{
Expand Down

0 comments on commit da38763

Please sign in to comment.