Created
August 29, 2023 11:04
-
-
Save MRezaSafari/5f82bc5d3611918b1a70b90061c3e53d to your computer and use it in GitHub Desktop.
Enforce allowed child types for custom components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
meta: { | |
type: "suggestion", | |
docs: { | |
description: "Enforce allowed child types for custom components", | |
category: "Best Practices", | |
recommended: true, | |
}, | |
}, | |
create(context) { | |
return { | |
JSXElement(node) { | |
const allowedChildrenMap = { | |
MySelect: ["MySelect.Option"], | |
}; | |
const { openingElement } = node; | |
const componentName = openingElement.name.name; | |
if (allowedChildrenMap[componentName]) { | |
const allowedChildren = allowedChildrenMap[componentName]; | |
for (const child of node.children) { | |
if ( | |
child.type === "JSXElement" && | |
!allowedChildren.includes(child.openingElement.name.name) | |
) { | |
context.report({ | |
node: child, | |
message: `Invalid child type for ${componentName}. Allowed child types: ${allowedChildren.join( | |
", " | |
)}`, | |
}); | |
} | |
} | |
} | |
}, | |
}; | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment