forked from jsx-eslint/eslint-plugin-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsx-inline-conditional.js
55 lines (48 loc) · 1.43 KB
/
jsx-inline-conditional.js
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
/**
* @fileoverview Enforce JSX inline conditional as a ternary
* @author Kevin Ingersoll
*/
'use strict';
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
inlineConditional: 'Conditional rendering in JSX should use a full ternary expression to avoid unintentionally rendering falsy values (i.e. zero)',
};
module.exports = {
meta: {
docs: {
description: 'Enforce JSX inline conditional as a ternary',
category: 'Possible Errors',
recommended: true,
url: docsUrl('jsx-inline-conditional'),
},
fixable: 'code',
messages,
schema: [],
},
create(context) {
const sourceCode = context.getSourceCode();
return {
JSXExpressionContainer(node) {
if (
node.expression.type === 'LogicalExpression'
&& node.expression.operator === '&&'
&& node.expression.right.type === 'JSXElement'
) {
context.report({
node,
messageId: 'inlineConditional',
fix: (fixer) => fixer.replaceText(
node,
`{${sourceCode.getText(
node.expression.left
)} ? ${sourceCode.getText(node.expression.right)} : null}`
),
});
}
},
};
},
};