Skip to content

Commit

Permalink
Add check for destructured createElement
Browse files Browse the repository at this point in the history
Due to the previous change of checking for `createElement` being called on
React, this left out the use case of a destructured import of
`createElement`.
  • Loading branch information
jomasti committed Jan 2, 2017
1 parent c6264d0 commit 47405b4
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/util/Components.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,20 @@ function componentRule(rule, context) {
node[property] &&
node[property].type === 'JSXElement'
;
var destructuredReactCreateElement = function () {
var variables = variableUtil.variablesInScope(context);
var variable = variableUtil.getVariable(variables, 'createElement');
if (variable !== null) {
var map = variable.scope.set;
// eslint-disable-next-line no-undef
if (map instanceof Map && map.has('React')) {
return true;
}
}
return false;
};
var returnsReactCreateElement =
destructuredReactCreateElement() ||
node[property] &&
node[property].callee &&
node[property].callee.object &&
Expand Down
20 changes: 20 additions & 0 deletions lib/util/variable.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,25 @@ function findVariable(variables, name) {
return false;
}

/**
* Find and return a particular variable in a list
* @param {Array} variables The variables list.
* @param {Array} name The name of the variable to search.
* @returns {Object} Variable if the variable was found, null if not.
*/
function getVariable(variables, name) {
var i;
var len;

for (i = 0, len = variables.length; i < len; i++) {
if (variables[i].name === name) {
return variables[i];
}
}

return null;
}

/**
* List all variable in a given scope
*
Expand Down Expand Up @@ -52,5 +71,6 @@ function variablesInScope(context) {

module.exports = {
findVariable: findVariable,
getVariable: getVariable,
variablesInScope: variablesInScope
};
17 changes: 17 additions & 0 deletions tests/lib/rules/display-name.js
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,12 @@ ruleTester.run('display-name', rule, {
'};'
].join('\n'),
parser: 'babel-eslint'
}, {
code: [
'const { createElement } = document;',
'createElement("a");'
].join('\n'),
parser: 'babel-eslint'
}],

invalid: [{
Expand Down Expand Up @@ -555,5 +561,16 @@ ruleTester.run('display-name', rule, {
errors: [{
message: 'Component definition is missing display name'
}]
}, {
code: [
'import React, { createElement } from "react";',
'export default (props) => {',
' return createElement("div", {}, "hello");',
'};'
].join('\n'),
parser: 'babel-eslint',
errors: [{
message: 'Component definition is missing display name'
}]
}]
});

0 comments on commit 47405b4

Please sign in to comment.