Improve the logic for determining if class is a React component #6
Comments
This is how I would implement import _ from 'lodash';
let isComponentClass,
isComponentIdentifier,
isReactComponentMemberExpression,
isReactIdentifier,
isRenderMethod;
/**
* @param {Object} node
* @return {Boolean}
*/
isRenderMethod = (node) => {
return _.every([
node.kind === 'method',
node.key.name === 'render'
]);
};
/**
* @param {Object} node
* @return {Boolean}
*/
isReactIdentifier = (node) => {
return _.every([
node.type === 'Identifier',
node.name === 'React'
]);
};
/**
* @param {Object} node
* @return {Boolean}
*/
isComponentIdentifier = (node) => {
return _.every([
node.type === 'Identifier',
node.name === 'Component'
]);
}
/**
* Checks if class extends React.Component.
*
* @param {Object} node
* @return {Boolean}
*/
isReactComponentMemberExpression = (node) => {
return _.every([
node.type === 'MemberExpression',
isReactIdentifier(node.object),
isComponentIdentifier(node.property)
]);
};
/**
* Checks if class has render method and class extends React.Component.
*
* @param {Object} node
* @return {Boolean}
*/
isComponentClass = (node) => {
let hasRenderMethod,
extendsReactComponent;
hasRenderMethod = Boolean(_.find(node.body.body, isRenderMethod));
extendsReactComponent = isReactComponentMemberExpression(node.superClass);
return _.every([
hasRenderMethod,
extendsReactComponent
]);
}; However, this assumes that |
React classes don't have to extend Component. You can check: it works just fine without it. Moreover, people might have custom base classes. (Yes it's a bad idea, but people do that occasionally.) |
On the other hand, people often add |
Sounds like a good idea. I am still getting my head around how to write Babel plugins. I am in the midst of writing one myself I am happy to own this issue and send a PR in a window of a few days. |
Let's discuss in #8. |
I have been looking at the code and
isCompomentishClass
function caught my eye as very loose:The only logic that is used to determine whether class declaration represents a React component is if it defines
render
method.Off top of my head, I do not have suggestions how to improve this beyond:
Component
.React.Component
.I still think thats pretty loose.
I am opening this issue to create a medium for discussion. Maybe someone will have better ideas.
The text was updated successfully, but these errors were encountered: