UNPKG

2.02 kBJavaScriptView Raw
1/**
2 * @fileoverview Prevent passing of children as props
3 * @author Benjamin Stepp
4 */
5
6'use strict';
7
8const docsUrl = require('../util/docsUrl');
9
10// ------------------------------------------------------------------------------
11// Helpers
12// ------------------------------------------------------------------------------
13
14/**
15 * Checks if the node is a createElement call with a props literal.
16 * @param {ASTNode} node - The AST node being checked.
17 * @returns {Boolean} - True if node is a createElement call with a props
18 * object literal, False if not.
19*/
20function isCreateElementWithProps(node) {
21 return node.callee
22 && node.callee.type === 'MemberExpression'
23 && node.callee.property.name === 'createElement'
24 && node.arguments.length > 1
25 && node.arguments[1].type === 'ObjectExpression';
26}
27
28// ------------------------------------------------------------------------------
29// Rule Definition
30// ------------------------------------------------------------------------------
31
32module.exports = {
33 meta: {
34 docs: {
35 description: 'Prevent passing of children as props.',
36 category: 'Best Practices',
37 recommended: true,
38 url: docsUrl('no-children-prop')
39 },
40 schema: []
41 },
42 create(context) {
43 return {
44 JSXAttribute(node) {
45 if (node.name.name !== 'children') {
46 return;
47 }
48
49 context.report({
50 node,
51 message: 'Do not pass children as props. Instead, nest children between the opening and closing tags.'
52 });
53 },
54 CallExpression(node) {
55 if (!isCreateElementWithProps(node)) {
56 return;
57 }
58
59 const props = node.arguments[1].properties;
60 const childrenProp = props.find((prop) => prop.key && prop.key.name === 'children');
61
62 if (childrenProp) {
63 context.report({
64 node,
65 message: 'Do not pass children as props. Instead, pass them as additional arguments to React.createElement.'
66 });
67 }
68 }
69 };
70 }
71};