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