diff --git a/index.js b/index.js index ca17399..198a3aa 100644 --- a/index.js +++ b/index.js @@ -36,6 +36,18 @@ function getReturnStatement(node) { return; } + if (node.type === 'ClassDeclaration') { + // For class-based components, find the render function, then its return statement + renderFunction = node.body?.body?.find( + (statement) => + statement.type === 'MethodDefinition' && + statement.key.name === 'render', + ); + return renderFunction.value?.body?.body?.find( + (statement) => statement.type === 'ReturnStatement', + ); + } + return node.type === 'VariableDeclaration' ? node.declarations?.[0]?.init?.body?.body?.find( (statement) => statement.type === 'ReturnStatement', @@ -99,7 +111,8 @@ const rules = { .filter( (child) => child.type === 'VariableDeclaration' || - child.type === 'FunctionDeclaration', + child.type === 'FunctionDeclaration' || + child.type === 'ClassDeclaration', ) .filter((child) => { let flag = false; diff --git a/test.js b/test.js index 326119a..f4c64c9 100644 --- a/test.js +++ b/test.js @@ -9,6 +9,7 @@ const { join } = require('path'); const singleComponent = `const temp = () => { ; };`; + const singleComponentError = `const temp = () => { ; };`; @@ -88,6 +89,46 @@ const fragmentsWontUpdate = `const Component = () => { };`; +const classComponent = `class Car extends React.Component { + render() { + return

Hi, I am a Car!

; + } +}`; + +const classComponentError = `class Car extends React.Component { + render() { + return

Hi, I am a Car!

; + } +}`; + +const classComponentNestedError = `class Car extends React.Component { + render() { + const Door = () => ( +

I am a door!

+ ); + return ( +
+ +

Hi, I am a Car!

+
+ ); + } +}`; + +const classComponentNested = `class Car extends React.Component { + render() { + const Door = () => ( +

I am a door!

+ ); + return ( +
+ +

Hi, I am a Car!

+
+ ); + } +}`; + const tests = { 'data-component': { // Require the actual rule definition @@ -142,6 +183,20 @@ const tests = { 'temp is missing the data-component attribute for the top-level element.', ], }, + { + code: classComponentError, + output: classComponent, + errors: [ + 'Car is missing the data-component attribute for the top-level element.', + ], + }, + { + code: classComponentNestedError, + output: classComponentNested, + errors: [ + 'Car is missing the data-component attribute for the top-level element.', + ], + }, { code: genericTestError, output: genericTest,