no-unstable-nested-components.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /**
  2. * @fileoverview Prevent creating unstable components inside components
  3. * @author Ari Perkkiö
  4. */
  5. 'use strict';
  6. const minimatch = require('minimatch');
  7. const Components = require('../util/Components');
  8. const docsUrl = require('../util/docsUrl');
  9. const astUtil = require('../util/ast');
  10. const isCreateElement = require('../util/isCreateElement');
  11. const report = require('../util/report');
  12. // ------------------------------------------------------------------------------
  13. // Constants
  14. // ------------------------------------------------------------------------------
  15. const COMPONENT_AS_PROPS_INFO = ' If you want to allow component creation in props, set allowAsProps option to true.';
  16. const HOOK_REGEXP = /^use[A-Z0-9].*$/;
  17. // ------------------------------------------------------------------------------
  18. // Helpers
  19. // ------------------------------------------------------------------------------
  20. /**
  21. * Generate error message with given parent component name
  22. * @param {string} parentName Name of the parent component, if known
  23. * @returns {string} Error message with parent component name
  24. */
  25. function generateErrorMessageWithParentName(parentName) {
  26. return `Do not define components during render. React will see a new component type on every render and destroy the entire subtree’s DOM nodes and state (https://reactjs.org/docs/reconciliation.html#elements-of-different-types). Instead, move this component definition out of the parent component${parentName ? ` “${parentName}” ` : ' '}and pass data as props.`;
  27. }
  28. /**
  29. * Check whether given text matches the pattern passed in.
  30. * @param {string} text Text to validate
  31. * @param {string} pattern Pattern to match against
  32. * @returns {boolean}
  33. */
  34. function propMatchesRenderPropPattern(text, pattern) {
  35. return typeof text === 'string' && minimatch(text, pattern);
  36. }
  37. /**
  38. * Get closest parent matching given matcher
  39. * @param {ASTNode} node The AST node
  40. * @param {Context} context eslint context
  41. * @param {Function} matcher Method used to match the parent
  42. * @returns {ASTNode} The matching parent node, if any
  43. */
  44. function getClosestMatchingParent(node, context, matcher) {
  45. if (!node || !node.parent || node.parent.type === 'Program') {
  46. return;
  47. }
  48. if (matcher(node.parent, context)) {
  49. return node.parent;
  50. }
  51. return getClosestMatchingParent(node.parent, context, matcher);
  52. }
  53. /**
  54. * Matcher used to check whether given node is a `createElement` call
  55. * @param {ASTNode} node The AST node
  56. * @param {Context} context eslint context
  57. * @returns {boolean} True if node is a `createElement` call, false if not
  58. */
  59. function isCreateElementMatcher(node, context) {
  60. return (
  61. astUtil.isCallExpression(node)
  62. && isCreateElement(context, node)
  63. );
  64. }
  65. /**
  66. * Matcher used to check whether given node is a `ObjectExpression`
  67. * @param {ASTNode} node The AST node
  68. * @returns {boolean} True if node is a `ObjectExpression`, false if not
  69. */
  70. function isObjectExpressionMatcher(node) {
  71. return node && node.type === 'ObjectExpression';
  72. }
  73. /**
  74. * Matcher used to check whether given node is a `JSXExpressionContainer`
  75. * @param {ASTNode} node The AST node
  76. * @returns {boolean} True if node is a `JSXExpressionContainer`, false if not
  77. */
  78. function isJSXExpressionContainerMatcher(node) {
  79. return node && node.type === 'JSXExpressionContainer';
  80. }
  81. /**
  82. * Matcher used to check whether given node is a `JSXAttribute` of `JSXExpressionContainer`
  83. * @param {ASTNode} node The AST node
  84. * @returns {boolean} True if node is a `JSXAttribute` of `JSXExpressionContainer`, false if not
  85. */
  86. function isJSXAttributeOfExpressionContainerMatcher(node) {
  87. return (
  88. node
  89. && node.type === 'JSXAttribute'
  90. && node.value
  91. && node.value.type === 'JSXExpressionContainer'
  92. );
  93. }
  94. /**
  95. * Matcher used to check whether given node is an object `Property`
  96. * @param {ASTNode} node The AST node
  97. * @returns {boolean} True if node is a `Property`, false if not
  98. */
  99. function isPropertyOfObjectExpressionMatcher(node) {
  100. return (
  101. node
  102. && node.parent
  103. && node.parent.type === 'Property'
  104. );
  105. }
  106. /**
  107. * Check whether given node or its parent is directly inside `map` call
  108. * ```jsx
  109. * {items.map(item => <li />)}
  110. * ```
  111. * @param {ASTNode} node The AST node
  112. * @returns {boolean} True if node is directly inside `map` call, false if not
  113. */
  114. function isMapCall(node) {
  115. return (
  116. node
  117. && node.callee
  118. && node.callee.property
  119. && node.callee.property.name === 'map'
  120. );
  121. }
  122. /**
  123. * Check whether given node is `ReturnStatement` of a React hook
  124. * @param {ASTNode} node The AST node
  125. * @param {Context} context eslint context
  126. * @returns {boolean} True if node is a `ReturnStatement` of a React hook, false if not
  127. */
  128. function isReturnStatementOfHook(node, context) {
  129. if (
  130. !node
  131. || !node.parent
  132. || node.parent.type !== 'ReturnStatement'
  133. ) {
  134. return false;
  135. }
  136. const callExpression = getClosestMatchingParent(node, context, astUtil.isCallExpression);
  137. return (
  138. callExpression
  139. && callExpression.callee
  140. && HOOK_REGEXP.test(callExpression.callee.name)
  141. );
  142. }
  143. /**
  144. * Check whether given node is declared inside a render prop
  145. * ```jsx
  146. * <Component renderFooter={() => <div />} />
  147. * <Component>{() => <div />}</Component>
  148. * ```
  149. * @param {ASTNode} node The AST node
  150. * @param {Context} context eslint context
  151. * @param {string} propNamePattern a pattern to match render props against
  152. * @returns {boolean} True if component is declared inside a render prop, false if not
  153. */
  154. function isComponentInRenderProp(node, context, propNamePattern) {
  155. if (
  156. node
  157. && node.parent
  158. && node.parent.type === 'Property'
  159. && node.parent.key
  160. && propMatchesRenderPropPattern(node.parent.key.name, propNamePattern)
  161. ) {
  162. return true;
  163. }
  164. // Check whether component is a render prop used as direct children, e.g. <Component>{() => <div />}</Component>
  165. if (
  166. node
  167. && node.parent
  168. && node.parent.type === 'JSXExpressionContainer'
  169. && node.parent.parent
  170. && node.parent.parent.type === 'JSXElement'
  171. ) {
  172. return true;
  173. }
  174. const jsxExpressionContainer = getClosestMatchingParent(node, context, isJSXExpressionContainerMatcher);
  175. // Check whether prop name indicates accepted patterns
  176. if (
  177. jsxExpressionContainer
  178. && jsxExpressionContainer.parent
  179. && jsxExpressionContainer.parent.type === 'JSXAttribute'
  180. && jsxExpressionContainer.parent.name
  181. && jsxExpressionContainer.parent.name.type === 'JSXIdentifier'
  182. ) {
  183. const propName = jsxExpressionContainer.parent.name.name;
  184. // Starts with render, e.g. <Component renderFooter={() => <div />} />
  185. if (propMatchesRenderPropPattern(propName, propNamePattern)) {
  186. return true;
  187. }
  188. // Uses children prop explicitly, e.g. <Component children={() => <div />} />
  189. if (propName === 'children') {
  190. return true;
  191. }
  192. }
  193. return false;
  194. }
  195. /**
  196. * Check whether given node is declared directly inside a render property
  197. * ```jsx
  198. * const rows = { render: () => <div /> }
  199. * <Component rows={ [{ render: () => <div /> }] } />
  200. * ```
  201. * @param {ASTNode} node The AST node
  202. * @param {string} propNamePattern The pattern to match render props against
  203. * @returns {boolean} True if component is declared inside a render property, false if not
  204. */
  205. function isDirectValueOfRenderProperty(node, propNamePattern) {
  206. return (
  207. node
  208. && node.parent
  209. && node.parent.type === 'Property'
  210. && node.parent.key
  211. && node.parent.key.type === 'Identifier'
  212. && propMatchesRenderPropPattern(node.parent.key.name, propNamePattern)
  213. );
  214. }
  215. /**
  216. * Resolve the component name of given node
  217. * @param {ASTNode} node The AST node of the component
  218. * @returns {string} Name of the component, if any
  219. */
  220. function resolveComponentName(node) {
  221. const parentName = node.id && node.id.name;
  222. if (parentName) return parentName;
  223. return (
  224. node.type === 'ArrowFunctionExpression'
  225. && node.parent
  226. && node.parent.id
  227. && node.parent.id.name
  228. );
  229. }
  230. // ------------------------------------------------------------------------------
  231. // Rule Definition
  232. // ------------------------------------------------------------------------------
  233. /** @type {import('eslint').Rule.RuleModule} */
  234. module.exports = {
  235. meta: {
  236. docs: {
  237. description: 'Disallow creating unstable components inside components',
  238. category: 'Possible Errors',
  239. recommended: false,
  240. url: docsUrl('no-unstable-nested-components'),
  241. },
  242. schema: [{
  243. type: 'object',
  244. properties: {
  245. customValidators: {
  246. type: 'array',
  247. items: {
  248. type: 'string',
  249. },
  250. },
  251. allowAsProps: {
  252. type: 'boolean',
  253. },
  254. propNamePattern: {
  255. type: 'string',
  256. },
  257. },
  258. additionalProperties: false,
  259. }],
  260. },
  261. create: Components.detect((context, components, utils) => {
  262. const allowAsProps = context.options.some((option) => option && option.allowAsProps);
  263. const propNamePattern = (context.options[0] || {}).propNamePattern || 'render*';
  264. /**
  265. * Check whether given node is declared inside class component's render block
  266. * ```jsx
  267. * class Component extends React.Component {
  268. * render() {
  269. * class NestedClassComponent extends React.Component {
  270. * ...
  271. * ```
  272. * @param {ASTNode} node The AST node being checked
  273. * @returns {boolean} True if node is inside class component's render block, false if not
  274. */
  275. function isInsideRenderMethod(node) {
  276. const parentComponent = utils.getParentComponent(node);
  277. if (!parentComponent || parentComponent.type !== 'ClassDeclaration') {
  278. return false;
  279. }
  280. return (
  281. node
  282. && node.parent
  283. && node.parent.type === 'MethodDefinition'
  284. && node.parent.key
  285. && node.parent.key.name === 'render'
  286. );
  287. }
  288. /**
  289. * Check whether given node is a function component declared inside class component.
  290. * Util's component detection fails to detect function components inside class components.
  291. * ```jsx
  292. * class Component extends React.Component {
  293. * render() {
  294. * const NestedComponent = () => <div />;
  295. * ...
  296. * ```
  297. * @param {ASTNode} node The AST node being checked
  298. * @returns {boolean} True if given node a function component declared inside class component, false if not
  299. */
  300. function isFunctionComponentInsideClassComponent(node) {
  301. const parentComponent = utils.getParentComponent(node);
  302. const parentStatelessComponent = utils.getParentStatelessComponent(node);
  303. return (
  304. parentComponent
  305. && parentStatelessComponent
  306. && parentComponent.type === 'ClassDeclaration'
  307. && utils.getStatelessComponent(parentStatelessComponent)
  308. && utils.isReturningJSX(node)
  309. );
  310. }
  311. /**
  312. * Check whether given node is declared inside `createElement` call's props
  313. * ```js
  314. * React.createElement(Component, {
  315. * footer: () => React.createElement("div", null)
  316. * })
  317. * ```
  318. * @param {ASTNode} node The AST node
  319. * @returns {boolean} True if node is declare inside `createElement` call's props, false if not
  320. */
  321. function isComponentInsideCreateElementsProp(node) {
  322. if (!components.get(node)) {
  323. return false;
  324. }
  325. const createElementParent = getClosestMatchingParent(node, context, isCreateElementMatcher);
  326. return (
  327. createElementParent
  328. && createElementParent.arguments
  329. && createElementParent.arguments[1] === getClosestMatchingParent(node, context, isObjectExpressionMatcher)
  330. );
  331. }
  332. /**
  333. * Check whether given node is declared inside a component/object prop.
  334. * ```jsx
  335. * <Component footer={() => <div />} />
  336. * { footer: () => <div /> }
  337. * ```
  338. * @param {ASTNode} node The AST node being checked
  339. * @returns {boolean} True if node is a component declared inside prop, false if not
  340. */
  341. function isComponentInProp(node) {
  342. if (isPropertyOfObjectExpressionMatcher(node)) {
  343. return utils.isReturningJSX(node);
  344. }
  345. const jsxAttribute = getClosestMatchingParent(node, context, isJSXAttributeOfExpressionContainerMatcher);
  346. if (!jsxAttribute) {
  347. return isComponentInsideCreateElementsProp(node);
  348. }
  349. return utils.isReturningJSX(node);
  350. }
  351. /**
  352. * Check whether given node is a stateless component returning non-JSX
  353. * ```jsx
  354. * {{ a: () => null }}
  355. * ```
  356. * @param {ASTNode} node The AST node being checked
  357. * @returns {boolean} True if node is a stateless component returning non-JSX, false if not
  358. */
  359. function isStatelessComponentReturningNull(node) {
  360. const component = utils.getStatelessComponent(node);
  361. return component && !utils.isReturningJSX(component);
  362. }
  363. /**
  364. * Check whether given node is a unstable nested component
  365. * @param {ASTNode} node The AST node being checked
  366. */
  367. function validate(node) {
  368. if (!node || !node.parent) {
  369. return;
  370. }
  371. const isDeclaredInsideProps = isComponentInProp(node);
  372. if (
  373. !components.get(node)
  374. && !isFunctionComponentInsideClassComponent(node)
  375. && !isDeclaredInsideProps) {
  376. return;
  377. }
  378. if (
  379. // Support allowAsProps option
  380. (isDeclaredInsideProps && (allowAsProps || isComponentInRenderProp(node, context, propNamePattern)))
  381. // Prevent reporting components created inside Array.map calls
  382. || isMapCall(node)
  383. || isMapCall(node.parent)
  384. // Do not mark components declared inside hooks (or falsy '() => null' clean-up methods)
  385. || isReturnStatementOfHook(node, context)
  386. // Do not mark objects containing render methods
  387. || isDirectValueOfRenderProperty(node, propNamePattern)
  388. // Prevent reporting nested class components twice
  389. || isInsideRenderMethod(node)
  390. // Prevent falsely reporting detected "components" which do not return JSX
  391. || isStatelessComponentReturningNull(node)
  392. ) {
  393. return;
  394. }
  395. // Get the closest parent component
  396. const parentComponent = getClosestMatchingParent(
  397. node,
  398. context,
  399. (nodeToMatch) => components.get(nodeToMatch)
  400. );
  401. if (parentComponent) {
  402. const parentName = resolveComponentName(parentComponent);
  403. // Exclude lowercase parents, e.g. function createTestComponent()
  404. // React-dom prevents creating lowercase components
  405. if (parentName && parentName[0] === parentName[0].toLowerCase()) {
  406. return;
  407. }
  408. let message = generateErrorMessageWithParentName(parentName);
  409. // Add information about allowAsProps option when component is declared inside prop
  410. if (isDeclaredInsideProps && !allowAsProps) {
  411. message += COMPONENT_AS_PROPS_INFO;
  412. }
  413. report(context, message, null, {
  414. node,
  415. });
  416. }
  417. }
  418. // --------------------------------------------------------------------------
  419. // Public
  420. // --------------------------------------------------------------------------
  421. return {
  422. FunctionDeclaration(node) { validate(node); },
  423. ArrowFunctionExpression(node) { validate(node); },
  424. FunctionExpression(node) { validate(node); },
  425. ClassDeclaration(node) { validate(node); },
  426. CallExpression(node) { validate(node); },
  427. };
  428. }),
  429. };